1

Here is an attempt to explain a bit clearer with code--

str = 'testfoostringfoo';
var regex = /foo$/;

if (str.match(regex) == true) {
    str.trim(regex);
    return str; //expecting 'testfoostring'
}

I'm looking for the simplest way to accomplish this using only javascript, though jQuery is available. Thanks for your time. :]



Fully functioning code with the help from @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
}
4

1 回答 1

2

你应该简单地replace

str = 'testfoostringfoo';
var regex = /foo$/;
str = str.replace(regex, '');
return str;

我删除了if,未找到replace时不影响字符串regex

请记住,它match返回一个匹配数组 ( ['foo']),因此true无论哪种方式比较都会失败:条件if(str.match(regex) == true)始终为假。
您正在寻找if(str.match(regex))if(regex.test(str))

请注意,这trim在 JavaScript 中有点新,它不接受参数,它只是删除空格。

于 2013-09-03T04:55:02.190 回答