我有一个可以从字符串中删除单词的函数。它是 :
var removeFromString = function(oldStr, fullStr) {
return fullStr.split(oldStr).join('');
};
我这样使用它:
console.log( removeFromString("Hello", "Hello World") ); // World
console.log( removeFromString("Hello", "Hello-World") ); // -World
但是主要的问题是:
var str = "Remove one, two, not three and four";
在这里,我们必须删除“一个”,“两个”和“四个”。这可以通过以下方式完成:
var a = removeFromString("one, two,", str); // Remove not three and four
var b = removeFromString("and four", a); // Remove not three
console.log(b); // Remove not three
在上面的示例中,我不得不两次使用该函数。我希望它是这样的:
var c = removeFromString(["one, two," , "and four"], str); // Remove not three
console.log(c); // Remove not three
是的,我实际上要升级removeFromString函数!我怎样才能做到这一点 ?
您可以join
从数组动态使用和构建正则表达式,并替换匹配的值
function removeFromString(arr,str){
let regex = new RegExp("\\b"+arr.join('|')+"\\b","gi")
return str.replace(regex, '')
}
console.log(removeFromString(["one, two," , "and four"],"Remove one, two, not three and four" ));
console.log(removeFromString(["one" , "and four"],"Remove one, two, not three and four" ));
console.log(removeFromString(["Hello"], "Hello World") )
为了覆盖单词匹配可以包含元字符的情况,您可以通过这种方式扩展上面的示例
function escape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
function removeFromString(arr, str) {
let escapedArr = arr.map(v=> escape(v))
let regex = new RegExp("(?:^|\\s)"+escapedArr.join('|') + "(?!\\S)", "gi")
return str.replace(regex, '')
}
console.log(removeFromString(["one, two,", "and four"], "Remove one, two, not three and four"));
console.log(removeFromString(["one", "and four"], "Remove one, two, not three and four"));
console.log(removeFromString(["Hello"], "Hello World"))
console.log(removeFromString(["He*llo"], "He*llo World"))
console.log(removeFromString(["Hello*"], "Hello* World"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句