我使用此正则表达式模式,.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);
该match()
方法在字符串中搜索与正则表达式的匹配项,然后将匹配项作为Array对象返回。
注意:如果正则表达式不包含g
修饰符(以执行全局搜索),则该match()
方法将仅返回字符串中的第一个匹配项。
null
如果找不到匹配项,则返回此方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句