Joe Joe - 4 months ago 6
Javascript Question

Substr starting at one character OR one other character

I have a function that takes an argument and needs to return that argument as a substring of it's original string:

var $ = function (selector) {
var elements = [];

var selectorSubstr = selector.substr(selector.lastIndexOf(".") || selector.lastIndexOf("#") + 1);

return selectorSubstr;

The arguments are all html elements:






I need the lastIndexOf to start at the last instance of either a '.' for the html class OR a '#' for the html id.

Currently the lastIndexOf only works for the first argument and doesn't take account of the '||' for 'or the other argument.

Any suggestions?

var $ = function (selector) {
  return selector.match(/[#\.][^\.#]+$/);

$("img.some_class")[0]; // ==> '.some_class'
$("div.some_class#some_id")[0]; // ==> #some_id
$("asbasifhwaehf"); // ==> null, no match