Is There a Version of JavaScript's String.Indexof() That Allows for Regular Expressions

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Combining a few of the approaches already mentioned (the indexOf is obviously rather simple), I think these are the functions that will do the trick:

function regexIndexOf(string, regex, startpos) {
var indexOf = string.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}

function regexLastIndexOf(string, regex, startpos) {
regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
if(typeof (startpos) == "undefined") {
startpos = string.length;
} else if(startpos < 0) {
startpos = 0;
}
var stringToWorkWith = string.substring(0, startpos + 1);
var lastIndexOf = -1;
var nextStop = 0;
while((result = regex.exec(stringToWorkWith)) != null) {
lastIndexOf = result.index;
regex.lastIndex = ++nextStop;
}
return lastIndexOf;
}

UPDATE: Edited regexLastIndexOf() so that is seems to mimic lastIndexOf() now. Please let me know if it still fails and under what circumstances.


UPDATE: Passes all tests found on in comments on this page, and my own. Of course, that doesn't mean it's bulletproof. Any feedback appreciated.

Javascript: indexOf with Regular Expression

Use String.prototype.search to get the index of a regex:

'https://example.com/#1234'.search(/#\d+$/); // 20

And RegExp.prototype.test if used for boolean checks:

/#\d+$/.test('https://example.com/#1234'); // true

The regex used for these examples are /#\d+$/ which will match literal # followed by 1 or more digits at the end of the string.

As pointed out in the comments you might just want to check location.hash:

/^#\d+$/.test(location.hash);

/^#\d+$/ will match a hash that contains 1 or more digits and nothing else.

JavaScript style/optimization: String.indexOf() v. Regex.test()

I ran some tests. The first method is slightly faster, but not by enough to make any real difference even under heavy use... except when sCompOp could potentially be a very long string. Because the first method searches a fixed-length string, its execution time is very stable no matter how long sCompOp gets, while the second method will potentially iterate through the entire length of sCompOp.

Also, the second method will potentially match invalid strings - "blah blah blah <= blah blah" satisfies the test...

Given that you're likely doing the work of parsing out the operator elsewhere, i doubt either edge case would be a problem. But even if this were not the case, a small modification to the expression would resolve both issues:

/^(>=|<=|<>)$/


Testing code:

function Time(fn, iter)
{
var start = new Date();
for (var i=0; i<iter; ++i)
fn();
var end = new Date();
console.log(fn.toString().replace(/[\r|\n]/g, ' '), "\n : " + (end-start));
}

function IndexMethod(op)
{
return (",>=,<=,<>,".indexOf("," + op + ",") != -1);
}

function RegexMethod(op)
{
return /(>=|<=|<>)/.test(op);
}

function timeTests()
{
var loopCount = 50000;

Time(function(){IndexMethod(">=");}, loopCount);
Time(function(){IndexMethod("<=");}, loopCount);
Time(function(){IndexMethod("<>");}, loopCount);
Time(function(){IndexMethod("!!");}, loopCount);
Time(function(){IndexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount);
Time(function(){IndexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);

Time(function(){RegexMethod(">=");}, loopCount);
Time(function(){RegexMethod("<=");}, loopCount);
Time(function(){RegexMethod("<>");}, loopCount);
Time(function(){RegexMethod("!!");}, loopCount);
Time(function(){RegexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount);
Time(function(){RegexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);
}

timeTests();

Tested in IE6, FF3, Chrome 0.2.149.30

What is the difference between indexOf() and search()?

If your situation requires the use of a regular expression, use the search() method, otherwise; the indexOf() method is more performant.

jQuery - Using indexOf() with match()

related question:
Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

But only for a case sensitive is more easy to do:

window.location.href.toLowerCase().indexOf("youtube.com/thumbnail?id=")

JavaScript Regex find first not equal to

You cannot put regex into indexOf. Use search instead.

See this for more info: Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

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

Maybe this can be useful and easier:

str.lastIndexOf(str.match(<your_regex_here>).pop());


Related Topics



Leave a reply



Submit