Given a user-inputted string with unknown regexes, I want to get the index of the first special regex character. (For my use case, the string will be a path.)
Examples:
foo/*/bar
-> 4
foo?/*/*/
-> 3
foofoo+?/**/
-> 6
Given a user-inputted string with unknown regexes, I want to get the index of the first special regex character. (For my use case, the string will be a path.)
Examples:
foo/*/bar
-> 4
foo?/*/*/
-> 3
foofoo+?/**/
-> 6
-
1
FWIW: Those probably aren't the desired path expressions. Usually such is done with 'glob expressions' and not actual regular expressions. Basic path globs would only consider
*
(and**
) and?
as special constructs. – user2864740 Commented Aug 6, 2015 at 1:34
4 Answers
Reset to default 5You could do something along the lines of what is below. Just update the function to include each character you're wanting to find the index of. Below should match what you gave as examples and return the proper values.
var match = /[*?+^${}[\]().|\\]/.exec("foo/*bar");
if (match) {
console.log(match.index);
}
To include all characters with special meaning in a regular expression, it would probably end up looking something like this:
var re = /[.*+?^${}()|[\]\\]/;
var match = re.exec('foo/*/bar');
if (match) {
console.log(match.index);
}
The expression itself is borrowed from MDN's documentation on how to escape literal string input to be used in a regular expression.
.search
This is what .search
was made for:
var index = "Foo/*/bar".search(/[*?+^${}[\]().|\\]/);
RegEx
You can use the .index
property of a RegExp function:
var index = ("Foo/*/bar".match(/[*?+^${}[\]().|\\]/) || {}).index
For me, it was find the index of the first special character if a string has:
var str = "fo@ao/*bar";
var match = /[^A-Za-z 0-9]/g.exec(str)
if(match){
console.log(match.index);
}