[英]Javascript: Get index of first special regex character in a string
给定一个用户输入的带有未知正则表达式的字符串,我想获取第一个特殊正则表达式字符的索引。 (对于我的用例,字符串将是路径。)
例子:
foo/*/bar
-> 4
foo?/*/*/
-> 3
foofoo+?/**/
-> 6
您可以按照以下内容进行操作。 只需更新函数以包括要查找其索引的每个字符即可。 以下内容应与您提供的示例相符,并返回正确的值。
var match = /[*?+^${}[\]().|\\]/.exec("foo/*bar");
if (match) {
console.log(match.index);
}
要在正则表达式中包含所有具有特殊含义的字符,可能最终看起来像这样:
var re = /[.*+?^${}()|[\]\\]/;
var match = re.exec('foo/*/bar');
if (match) {
console.log(match.index);
}
该表达式本身是从MDN的文档中借用的,该文档介绍了如何转义要在正则表达式中使用的文字字符串输入。
.search
这是.search
目的:
var index = "Foo/*/bar".search(/[*?+^${}[\]().|\\]/);
您可以使用RegExp函数的.index
属性:
var index = ("Foo/*/bar".match(/[*?+^${}[\]().|\\]/) || {}).index
对我来说,如果字符串具有以下内容,则查找第一个特殊字符的索引:
var str = "fo@ao/*bar";
var match = /[^A-Za-z 0-9]/g.exec(str)
if(match){
console.log(match.index);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.