标题说明了一切
即
" fooHello World" => "Hello World"
"fooBing space in the middlefoo " => "Bing space in the middle"
" foo " => ""
" fooHellofoo " => "Hello"
答案 0 :(得分:0)
您可以使用trim()
删除前导/尾随空格。
您可以使用replace()
通过正则表达式定位foo
并将其删除。尝试运行以下代码段:
const trimAndRemoveFoo = (str) => {
return str.trim().replace(/foo/g, '');
}
// log trimAndRemoveFoo function with sample strings
console.log(trimAndRemoveFoo(" fooHello World"));
console.log(trimAndRemoveFoo("fooBing space in the middlefoo "));
console.log(trimAndRemoveFoo(" foo "));
console.log(trimAndRemoveFoo(" fooHellofoo "));

答案 1 :(得分:-1)
您可以使用replace
进行正则表达式搜索,并使用以下正则表达式/\W*foo\W*/g
const strs = [
" fooHello World",
"fooBing space in the middlefoo ",
" foo ",
" fooHellofoo "
];
const results = strs.map((str) => {
return str.replace(/\W*foo\W*/g, '');
});
console.log(results)