【问题标题】:regex to remove multiple comma and spaces from string in javascript [closed]正则表达式从javascript中的字符串中删除多个逗号和空格[关闭]
【发布时间】:2021-10-21 22:20:14
【问题描述】:

我有一个类似的字符串

var str=" , this,  is a ,,, test string , , to find regex,,in js.  , ";

字符串的开头、中间和结尾有多个空格,带逗号。我需要这个字符串在

var str="this is a test string to find regex in js.";

我在论坛中发现了许多正则表达式,分别删除空格、逗号,但我无法加入它们以删除两者。

如果可能,请解释正则表达式语法。

提前致谢

【问题讨论】:

  • “请尽可能解释正则表达式语法” - 你看过MDN's regex pageregular-expressions.info吗?
  • 在其他字符串中,我需要替换多个空格和多个逗号与单个逗号,例如 var str=",这是替换 ,、多个逗号和空格。,";我需要从字符串的开头和结尾替换逗号,用一个空格替换多个空格,并将字符串中的多个逗号替换为单个逗号。 as var result_str="this is to replace ,multiple comma and space";
  • @Dashrath 你能把它放在你的问题中吗?什么时候不应该完全删除逗号?

标签: javascript regex


【解决方案1】:

您可以用空格替换每个空格和逗号,然后修剪那些尾随空格:

var str=" , this,  is a ,,, test string , , to find regex,,in js.  , ";
res = str.replace(/[, ]+/g, " ").trim();

jsfiddle demo

【讨论】:

  • 感谢一个很好的答案,但是 str.replace(/[, ]+/g, " ").trim() 和 str.replace(/[, ]+/ 之间的真正区别是什么g, " ") 没有 trim() ?刚刚检查,结果是一样的(或者我可能在某个地方弄错了?)
  • @NikolayTalanov 开头和结尾的空格,如果你有****hello***,它最终会变成*hello*。使用trim() 可以消除这种情况。注意这里使用 * 表示空格,以便清楚起见...
  • @Lloyd 完全正确:)
【解决方案2】:

您可以为此使用 reg ex

/[,\s]+|[,\s]+/g

var str= "your string here";
//this will be new string after replace
str = str.replace(/[,\s]+|[,\s]+/g, 'your string here');

RegEx Explained and Demo

【讨论】:

  • 你应该使用 regex101 上的替换功能 :)
【解决方案3】:

试试这样的:

var new_string = old_string.replace(/[, ]+/g,' ').trim();

如果我们要将其分解,正则表达式就是[, ]+\s 表示任何空白字符,, 是文字逗号。 [] 是一个字符集(想想数组),+ 表示一个或多个匹配项。

我们在末尾添加一个/g,以便它进行全局搜索和替换,否则它只会针对一个匹配项进行。

【讨论】:

  • 这是产生结果为 new_string="thisisteststringtofindregexinjs";
  • 糟糕,我认为现在已修复。
  • 它只是用空格替换逗号,导致单词之间有几个空格的字符串。
【解决方案4】:

你应该可以使用

str.replace(/,/g," ");

'g'是关键,你可能需要使用[,]

【讨论】:

    猜你喜欢
    • 2020-01-03
    • 2018-11-20
    • 2016-08-17
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多