我将这个正则表达式模式与 .match()
一起使用,它按预期工作。但是,尝试使其与 .replace()
一起工作似乎失败了,我无法理解原因。也许我需要一些新的眼睛..
(function(){
var testRegex = /^\/Monkey\/tooth\d+\/$/g;
var testStr = '/Monkey/tooth8/';
var testMatch = testStr.match(testRegex,'');
var newString = testStr.replace(testRegex,'');
alert(newString);
if(nullCheck(testMatch) == false){alert('false');}else{alert('true');}
})()
我希望警报会提醒一个空框,但它只是提醒与 testStr 相同的事情。我从中缺少什么,我最终想摆脱字符串(如果它存在)。示例输出
/Monkey/Tooth10/Hello/World => Hello/World
/Monkey/Tooth10/GoodBye/World => GoodBye/World
最佳答案
删除 ^
和 $
以避免整个字符串匹配,分别在字符串的开头和结尾断言位置。
你可以试试
\/Monkey\/tooth\d+\/
或者只是删除$
^\/Monkey\/tooth\d+\/
示例代码:(使用i
修饰符进行忽略大小写匹配)
var re = /\/Monkey\/tooth\d+\//gi;
var str = '/Monkey/Tooth10/Hello/World';
var subst = '';
var result = str.replace(re, subst);
var matchedString = str.match(re);
<小时/>
JavaScript String match() Method
match()
方法在字符串中搜索与正则表达式的匹配项,并将匹配项作为 Array 对象返回。
注意:如果正则表达式不包含 g
修饰符(用于执行全局搜索),则 match()
方法将仅返回字符串中的第一个匹配项。
如果未找到匹配项,此方法将返回 null
。
关于javascript - 正则表达式替换失败,我不明白原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25433849/