Search code examples
javascriptregexsubstrlastindexof

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:

$("div") => "div"

&

$("img.some_class") => "some_class"

&

$("div.some_class#some_id") => "some_id"

&

$("div#some_id.some_class") => "some_class"

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?


Solution

  • var $ = function (selector) {
      return selector.match(/[#\.][^\.#]+$/);
    }
    
    $("img.some_class")[0]; // ==> '.some_class'
    $("div.some_class#some_id")[0]; // ==> #some_id
    $("asbasifhwaehf"); // ==> null, no match
    

    EDIT: addressing @Joe's requirement, I make this edit to return the whole input string in case it does not contain # or .

    var $ = function (selector) {
      var arr = selector.match(/[#\.][^\.#]+$/);
      return arr ? arr[0] : selector
    }
    
    $("img.some_class"); // ==> '.some_class'
    $("div.some_class#some_id"); // ==> '#some_id'
    $("asbasifhwaehf"); // ==> 'asbasifhwaehf', no match
    

    to get the string without the . or # prefix, just call

    $("div.some_class#some_id").slice(1); // ==> 'some_id'
    

    You can also return arr ? arr[0].slice(1) : selector in the function, but then you have no way to tell if it's a class or an id or the whole string (no match case) just from the return value