假设我有一个字符串hello
,我希望它从字符串中减去。
hello_my_good_world
my_hello_good_world
my_good_hello_world
以上字符串的输出必须分别如下所示。
my_good_world
my_good_world
my_good_world
请注意,下划线_
的删除方式也是如此。如果字符串hello
在开头,则应删除下划线。如果在中间,则应删除下一个或上一个下划线。因此,我没有重复的下划线。如果子字符串位于末尾,则应删除先前的下划线。我尝试使用JS replace
方法,但只能删除子字符串。还没有想出如何处理重复的下划线来消除它们。
答案 0 :(得分:5)
使用.replace(/hello_|_hello/g,'')
console.log("hello_my_good_world".replace(/hello_|_hello/g,''))
console.log("my_hello_good_world".replace(/hello_|_hello/g,''))
console.log("my_good_hello_world".replace(/hello_|_hello/g,''))
答案 1 :(得分:1)
您还可以进行多次替换。
const tests = [
'hello_my_good_world',
'my_hello_good_world',
'my_good_hello_world',
]
const replaced = tests.map(s => {
const replacement = s
.replace('hello', '') // eliminate 'hello'
.replace('__', '_') // eliminate double underscore
.replace(/^_/g, '') // eliminate leading underscore
.replace(/_$/g, '') // eliminate trailing underscore
return replacement;
});
console.log({
replaced,
});
答案 2 :(得分:1)
另一种选择是在_
上分割字符串,过滤掉"hello"
,然后与_
重新加入:
console.log("hello_my_good_world".split("_").filter(s => s !== "hello").join("_"))
console.log("my_hello_good_world".split("_").filter(s => s !== "hello").join("_"))
console.log("my_good_hello_world".split("_").filter(s => s !== "hello").join("_"))