【问题标题】:Remove spaces and quotes outside words and leave one space between words去掉单词外的空格和引号,单词之间留一个空格
【发布时间】:2019-04-22 14:10:51
【问题描述】:

我有一个带引号和空格的字符串,例如' TEST 123 '" TEST 123 "。如何删除单词外的空格和引号,并在单词之间留一个空格。预期结果:TEST 123

【问题讨论】:

  • 请与我们分享您的尝试
  • 这里是你的逻辑,trimsplittrimjoin

标签: javascript regex


【解决方案1】:

你可以使用这个正则表达式,

^[ '"]+|[ '"]+$|( ){2,}

并用$1 替换它,其中$1 捕获单个空格,但例如有两个或多个空格。

这里,^[ '"]+ 匹配字符串开头的一个或多个空格或单引号或双引号,同样[ '"]+$ 也匹配字符串末尾的任何空格或单引号或双引号一个或多个,并替换为空字符串其中 ( ){2,} 匹配(仍待在字符串中间匹配)被替换为 group1 中捕获的单个空格。

Regex Demo

示例 JS 演示,

var arr = ["' TEST   123  '",'"  TEST  123  "'];

for (s of arr) {
 console.log(s + " --> " + s.replace(/^[ '"]+|[ '"]+$|( ){2,}/g,'$1'));
}

【讨论】:

    【解决方案2】:

    remove extra spaces in string javascript

    newString = string.replace(/\s+/g,''); // "thiscontainsspaces"

    newString = string.replace(/\s+/g,' ').trim();

    【讨论】:

    • 字符串包含双引号或单引号,而不仅仅是空格
    • 单引号......你基本上用空白值替换任何适合正则表达式的东西
    • newString = string.replace(/[ '"]+/g, ' ').trim() - 它在单词前留下空格
    猜你喜欢
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多