首页 文章

如何使用JavaScript从字符串中删除空格?

提问于
浏览
412

如何删除字符串中的空格?例如:

输入: '/var/www/site/Brand new document.docx'
输出: '/var/www/site/Brandnewdocument.docx'

谢谢

7 回答

  • 48

    SHORTEST and FASTESTstr.replace(/ /g, '');


    基准测试:

    在这里我的结果 - (2018.07.13)MacO High Sierra 10.13.3在Chrome 67.0.3396(64位),Safari 11.0.3(13604.5.6),Firefox 59.0.2(64位)):

    SHORT字符串

    短字符串类似于OP问题的例子

    enter image description here

    所有浏览器上最快的解决方案是 / /g (regexp1a) - Chrome 17.7M(操作/秒),Safari 10.1M,Firefox 8.8M . 所有浏览器最慢的是 split-join 解决方案 . 将 `` 更改为 \s 或将 +i 添加到regexp会降低处理速度 .

    LONG字符串

    对于大约3个百万字符串的字符串结果是:

    • regexp1a :Safari 50.14 ops / sec,Firefox 18.57,Chrome 8.95

    • regexp2b :Safari 38.39,Firefox 19.45,Chrome 9.26

    • split-join :Firefox 26.41,Safari 23.10,Chrome 7.98,

    您可以在您的机器上运行它:https://jsperf.com/remove-string-spaces/1

  • 7
    var input = '/var/www/site/Brand new document.docx';
    
    //remove space
    input = input.replace(/\s/g, '');
    
    //make string lower
    input = input.toLowerCase();
    
    alert(input);
    

    Click here for working example

  • 2
    var a = b = " /var/www/site/Brand new   document.docx ";
    
    console.log( a.split(' ').join('') );
    console.log( b.replace( /\s/g, '') );
    

    两种方法!

  • 12

    关注@rsplak回答:实际上,使用split / join方式比使用regexp更快 . 看表演test case

    所以

    var result = text.split(' ').join('')

    运作速度比

    var result = text.replace(/\s+/g, '')

    在小文本上,这是不相关的,但对于时间很重要的情况,例如在文本分析器中,尤其是在与用户交互时,这很重要 .


    另一方面, \s+ 处理更多种类的空格字符 . 在 \n\t 之间,它也匹配 \u00a0 字符,这就是   在使用 textDomNode.nodeValue 获取文本时的内容 .

    所以我认为这里的结论可以如下:如果你只需要替换空格 ' ' ,请使用split / join . 如果符号类可以有不同的符号 - 请使用 replace(/\s+/g, '')

  • 891

    你可以尝试使用这个:

    input.split(' ').join('');
    
  • 5

    这个?

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

    var str = '/var/www/site/Brand new document.docx';
    
    document.write( str.replace(/\s/g, '') );
    

    Update: 基于this question,这个:

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

    是一个更好的解决方案它产生相同的结果,但它更快 .

    The Regex

    \s 是"whitespace"的正则表达式, g 是"global"标志,意味着匹配ALL \s (空格) .

    可以找到 + 的一个很好的解释here .

    作为旁注,您可以将单引号之间的内容替换为您想要的任何内容,这样您就可以用任何其他字符串替换空格 .

  • 3
    var output = '/var/www/site/Brand new document.docx'.replace(/ /g, ""); 
        or
      var output = '/var/www/site/Brand new document.docx'.replace(/ /gi,"");
    

    注意:虽然使用'g'或'gi'来删除空格,但两者的行为都相同 .

    如果我们在替换函数中使用'g',它将检查完全匹配 . 但如果我们使用'gi',它会忽略区分大小写 .

    供参考click here .

相关问题