【发布时间】:2020-08-03 19:34:25
【问题描述】:
我有一个字符串,我正试图从中删除单词“and”。我正在尝试通过在 javascript 中使用 .replace 方法。我可以删除“和”这个词,但最终结果不是我所期望的。
我希望我的字符串返回类似于console.log(testString),其中整个字符串返回为"i-have-a-test-test-test",中间没有任何空格。目前,我对console.log(newString) 的尝试返回的字符串在每个单词之间没有-。
我的预期结果是返回结果为:
I-have-a-test-test-test
const string = "I have a test and test and test"
const newString = string.replace(/([^a-zA-Z0-9]*|\s*)\s\and/g, '-')
const testString = string.replace(/([^a-zA-Z0-9]*|\s*)\s/g, '-')
console.log(newString)
console.log(testString)
【问题讨论】:
-
你想要
string.replace(/\band\b/g, "").split(/ +/).join("-")这样的东西吗? -
这能回答你的问题吗? How to replace all occurrences of a string?
-
同样相关:Strip everything but letters and numbers and replace spaces that are in the sentence with hyphens - 它的工作原理相同,但您可以替换
and,然后将所有空格替换为破折号。
标签: javascript string