Replace all whitespace characters

前端 未结 10 1027
北荒
北荒 2020-12-04 07:39

I want to replace all occurrences of white space characters (space, tab, newline) in JavaScript.
How to do so?

I tried:

str.replace(/ /gi, \"X\         


        
相关标签:
10条回答
  • 2020-12-04 08:07

    Try this:

    str.replace(/\s/g, "X")
    
    0 讨论(0)
  • 2020-12-04 08:09

    If you use

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

    it replaces all whitespaces. For example:

    var str = "hello my world";
    str.replace(/\s/g, "") //the result will be "hellomyworld"
    
    0 讨论(0)
  • 2020-12-04 08:12

    You could use the function trim

    let str = ' Hello World ';

    alert (str.trim());

    All the front and back spaces around Hello World would be removed.

    0 讨论(0)
  • 2020-12-04 08:12

    I've used the "slugify" method from underscore.string and it worked like a charm:

    https://github.com/epeli/underscore.string#slugifystring--string

    The cool thing is that you can really just import this method, don't need to import the entire library.

    0 讨论(0)
  • 2020-12-04 08:14

    Actually it has been worked but

    just try this.

    take the value /\s/g into a string variable like

    String a = /\s/g;
    
    str = str.replaceAll(a,"X");
    
    0 讨论(0)
  • 2020-12-04 08:21

    You want \s

    Matches a single white space character, including space, tab, form feed, line feed.

    Equivalent to

    [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
    

    in Firefox and [ \f\n\r\t\v] in IE.


    str = str.replace(/\s/g, "X");
    
    0 讨论(0)
提交回复
热议问题