【问题标题】:JS: How to remove white spaces only from inside of stringJS:如何仅从字符串内部删除空格
【发布时间】:2017-05-20 03:29:24
【问题描述】:

我只需要在 javascript 语言中从字符串内部删除空格。左右两边可以有那个空格。我没有找到解决方案...

也许是一些本机功能?或者sombedy有一些正则表达式?

我只有:

str = str.replace(/\s+/g, '');

但它也会从侧面删除空格。

我想要:

var str = "   s dasd   asd sad sa d   ";
str = str.replace(/\s+/g, '');
// output
"   sdasdasdsadsad   ";

【问题讨论】:

  • 你能举一个你想要的例子吗?
  • 我添加了小例子

标签: javascript string whitespace removing-whitespace


【解决方案1】:

您可以匹配并捕获前导/尾随空格并使用反向引用在结果中恢复,并删除所有其他空格。

var str = "   some text  ";
str = str.replace(/(^\s+|\s+$)|\s+/g, '$1');
console.log("'",str,"'");

模式详情

  • (^\s+|\s+$) - 第 1 组捕获一个或多个空格 1) 在字符串开头 (^\s+) 或 2) 在字符串结尾 (\s+$)
  • | - 或
  • \s+ - 字符串中其他任何地方的 1+ 个空格。

$1 是对插入到结果字符串中的捕获组内容的反向引用。

也支持 ,使用交替,(?:\s| )

console.log("   s dasd   asd sad sa d   ".replace(/(^(?:\s| )+|(?:\s| )+$)|(?:\s| )+/g, '$1'));

【讨论】:

    猜你喜欢
    • 2012-09-05
    • 2021-06-24
    • 2018-02-08
    • 2021-09-04
    • 2012-09-16
    • 1970-01-01
    • 2020-02-02
    • 2011-09-21
    • 2017-11-20
    相关资源
    最近更新 更多