简体   繁体   中英

Javascript: Get index of first special regex character in a string

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

You 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM