Replace all whitespace characters

前端 未结 10 1028
北荒
北荒 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:21

    We can also use this if we want to change all multiple joined blank spaces with a single character:

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

    See it in action here: https://regex101.com/r/d9d53G/1

    Explanation

    / \s+ / g

    • \s+ matches any whitespace character (equal to [\r\n\t\f\v ])
    • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

    • Global pattern flags
      • g modifier: global. All matches (don't return after first match)
    0 讨论(0)
  • 2020-12-04 08:25

    Have you tried the \s?

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

    \s is a meta character that covers all white space. You don't need to make it case-insensitive — white space doesn't have case.

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

    Not /gi but /g

    var fname = "My Family File.jpg"
    fname = fname.replace(/ /g,"_");
    console.log(fname);
    

    gives

    "My_Family_File.jpg"
    
    0 讨论(0)
提交回复
热议问题