Joe Joe - 1 year ago 85
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?

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

$("img.some_class")[0]; // ==> '.some_class'
$("div.some_class#some_id")[0]; // ==> #some_id
$("asbasifhwaehf"); // ==> null, no match
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download