最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

Share Improve this question edited Aug 6, 2015 at 1:40 Script47 14.6k4 gold badges48 silver badges68 bronze badges asked Aug 6, 2015 at 1:12 user2946797user2946797 1912 silver badges11 bronze badges 1
  • 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
Add a ment  | 

4 Answers 4

Reset to default 5

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);
}
发布评论

评论列表(0)

  1. 暂无评论