这是尝试用代码解释一下 -
str = 'testfoostringfoo';
var regex = /foo$/;
if (str.match(regex) == true) {
str.trim(regex);
return str; //expecting 'testfoostring'
}
我正在寻找使用javascript实现此目的的最简单方法,尽管jQuery可用。谢谢你的时间。 :
在@Kobi的帮助下完全正常运行的代码 -
var str = 'testfoostringfoo';
var regex = /f00$/;
if (str.match(regex)) {
str = str.replace(regex, '');
return str; //returns 'testfoostring' when the regex exists in str
}
答案 0 :(得分:2)
你应该只是replace
:
str = 'testfoostringfoo';
var regex = /foo$/;
str = str.replace(regex, '');
return str;
我删除了if
,replace
在找不到regex
时不会影响字符串。
请注意,match
会返回一系列匹配项(['foo']
),因此与true
的比较无论如何都会失败:if(str.match(regex) == true)
中的条件始终为false。
您正在寻找if(str.match(regex))
或if(regex.test(str))
。
请注意trim
在JavaScript中有点新,并且它不接受参数,它只是删除空格。