【问题标题】:Javascript all dots replace with space (Why my code is not working)Javascript 所有点都替换为空格(为什么我的代码不起作用)
【发布时间】:2020-03-04 23:24:31
【问题描述】:

我正在尝试替换所有 .有空格。

我已经完成了正则表达式

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

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

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

【问题讨论】:

  • 这不是它返回的内容。
  • 让你成为了一个sn-p。您的代码执行您要求它执行的操作。您可能还想将两个空格变为一个
  • 所以基本上你只想在字符串中留下字母和空格?
  • 如果是,你可能会更好voice.match(/\w+/g).join(' ')

标签: javascript


【解决方案1】:

你可以试试这个

var voice =  "I am a student of the .... university."
voice = voice.replace(/\./g, '').replace(/\s{2,}/g, ' ')

console.log(voice);

【讨论】:

  • var voice = voice.replace(/\./g, '')console.log('voice',voice)
  • 在“the”和“university”之间留下两个空格。
  • 您的更新 still 在“the”和“university”之间留下两个空格,但会(完全)删除字符串中的两个空格elsewhere,可能最终将单词连接在一起。例如,"I am a student at the .... university"student 后面的两个空格)变为"I am a studentat the university"student 后面没有空格,其中两个在theuniversity 之间)。
  • 其实字符串来自数据库,我的查询是如何从字符串中删除所有点
  • 这个答案(和我的一样)回答了最初提出的问题,但现在已被编辑。原来 OP 给了我们不正确的样本数据。我建议删除答案(因为已经有一个接受的答案)。
【解决方案2】:

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

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)

如果你不断想出更多的标点符号,那么你就有一个永无止境的问题:

Are there character collections for all international full stop punctuations?

所以也许这样更好:

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)

【讨论】:

  • 这不适用于“我是……学校的学生”
  • 你的句号不是句号,而是省略号
  • 我在内容列表中添加了省略号。 |…|
  • @RahulJat 我们可以想象更多:stackoverflow.com/questions/9506869/…
  • @RahulJat - 当您提出问题时,请确保您提供的信息是准确的。请注意,该主题中有五个不同的人提供了他们的时间来帮助您,结果发现您在问题中提供了不正确的测试数据。
【解决方案3】:

无论如何你都不喜欢正则表达式。性能也不差。

var voice = "I am a student of the .... university."
voice  = voice .split('.').join(' ');

【讨论】:

  • 这样会留下多个空格
  • 这个答案(和我的一样)回答了最初提出的问题,但现在已被编辑。事实证明,OP 给了我们不正确的样本数据。我建议删除答案(因为已经有一个接受的答案)。
猜你喜欢
  • 2013-11-26
  • 2015-09-28
  • 2021-09-30
  • 1970-01-01
  • 2018-12-01
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
  • 2014-05-24
相关资源
最近更新 更多