【问题标题】:Remove space in the middle of a string with $.trim? [duplicate]使用 $.trim 删除字符串中间的空格? [复制]
【发布时间】:2017-05-16 19:53:35
【问题描述】:

我想用$.trim()去掉字符串中间的空格,例如:

console.log($.trim("hello,           how are you?       "));

我明白了:

hello,           how are you?

我怎样才能得到

hello, how are you?

谢谢。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

一种解决方案是使用 javascript replace

我建议你使用regex

var str="hello,           how are you?       ";
str=str.replace( /\s\s+/g, ' ' );
console.log(str);

另一个简单的方法是使用.join() 方法。

var str="hello,           how are you?       ";
str=str.split(/\s+/).join(' ');
console.log(str);

【讨论】:

    【解决方案2】:

    您可以使用正则表达式将所有连续空格\s\s+ 替换为单个空格作为字符串' ',这将消除空格并仅保留一个空格,然后$.trim 将负责开头和/或结束空格:

    var string = "hello,           how are you?       ";
    console.log($.trim(string.replace(/\s\s+/g, ' ')));
    

    【讨论】:

    • 谢谢,祝大家新年快乐!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 2012-11-19
    • 2018-05-15
    • 2023-01-31
    • 2017-04-14
    相关资源
    最近更新 更多