Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: String search for regex, starting at the end of the string

Is there a javascript string function that search a regex and it will start the search at the end?

If not, what is the fastest and/or cleanest way to search the index of a regex starting from the end?

example of regex:

/<\/?([a-z][a-z0-9]*)\b[^>]*>?/gi
like image 637
Marl Avatar asked Oct 18 '13 09:10

Marl


3 Answers

Maybe this can be useful and easier:

str.lastIndexOf(str.match(<your_regex_here>).pop());
like image 198
Raul Bejarano Avatar answered Oct 03 '22 02:10

Raul Bejarano


Perhaps something like this is suitable for you?

Javascript

function lastIndexOfRx(string, regex) {
    var match = string.match(regex);

    return  match ? string.lastIndexOf(match.slice(-1)) : -1;
}

var rx = /<\/?([a-z][a-z0-9]*)\b[^>]*>?/gi;

console.log(lastIndexOfRx("", rx));
console.log(lastIndexOfRx("<i>it</i><b>bo</b>", rx));

jsFiddle

And just for interest, this function vs the function that you choose to go with. jsperf

This requires that you format your regex correctly for matching exactly the pattern you want and globally (like given in your question), for example /.*(<\/?([a-z][a-z0-9]*)\b[^>]*>?)/i will not work with this function. But what you do get is a function that is clean and fast.

like image 31
Xotic750 Avatar answered Oct 03 '22 03:10

Xotic750


You may create a reverse function like:

function reverse (s) {
  var o = '';
  for (var i = s.length - 1; i >= 0; i--)
    o += s[i];
  return o;
}

and then use

var yourString = reverse("Your string goes here");
var regex = new Regex(your_expression);
var result = yourString.match(regex);

Another idea: if you want to search by word in reverse order then

function reverseWord(s) {
   var o = '';
   var split = s.split(' ');

  for (var i = split.length - 1; i >= 0; i--)
    o += split[i] + ' ';
  return o;
}

var yourString = reverseWord("Your string goes here");
var regex = new Regex(your_expression);
var result = yourString.match(regex);
like image 24
Snake Eyes Avatar answered Oct 03 '22 02:10

Snake Eyes