Javascript所有点都用空格替换(为什么我的代码不起作用)

Rah*_*Jat 1 javascript

我正在尝试全部取代。与空间。

我已经完成了正则表达式

var voice = "I am student of …… School"
voice = voice.replace(/(~|`|!|@|#|$|%|^|&|\*|\(|\)|{|}|\[|\]|;|:|\"|'|<|,|\.|>|\?|\/|\\|\||-|_|\+|=)/g, "");
console.log(voice)
Run Code Online (Sandbox Code Playgroud)

它返回 "I am a student of the .... university"

但我想要这样的字符串=> "I am a student of the university"

mpl*_*jan 5

当您随后用一个空格替换多个空格时,您的代码起作用

var voice = "I am student of the .....University, not the …… School"
console.log(voice)
voice = voice.replace(/(~|`|!|@|#|$|%|^|&|\*|\(|\)|{|}|\[|\]|;|:|\"|'|<|,|\.|…|>|\?|\/|\\|\||-|_|\+|=)/g, "")
             .replace(/ +/g," "); // or /\s+/g
console.log(voice)
Run Code Online (Sandbox Code Playgroud)

如果您继续提出更多的标点符号,那么您将面临一个永无止境的问题:

是否有所有国际句点标点符号集?

所以也许这更好:

var voice = "I am student of the .....University, not the …… School"
console.log(voice)
voice = voice.replace(/\W/g, " ")
             .replace(/ +/g," "); // or /\s+/g
console.log(voice)
Run Code Online (Sandbox Code Playgroud)

  • @RahulJat-请确保在提出问题时确保所提供的信息准确无误。请注意,该线程中的“五个不同的人”提供了他们的时间来尝试帮助您,却发现您在问题中输入了错误的测试数据。 (3认同)