Javascript 替换所有空白字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6507056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace all whitespace characters
提问by Sourav
I want to replace all occurrences of white space characters (space, tab, newline) in JavaScript.
How to do so?
我想替换 JavaScript 中所有出现的空白字符(空格、制表符、换行符)。
怎么做?
I tried:
我试过:
str.replace(/ /gi, "X")
回答by Alex K.
回答by Quentin
\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.
\s
是一个元字符,涵盖所有空白。你不需要让它不区分大小写——空白没有大小写。
str.replace(/\s/g, "X")
回答by Milos Stankovic
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
在这里查看它的实际效果:https: //regex101.com/r/d9d53G/1
Explanation
解释
/
\s+
/ g
/
\s+
/克
\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)
\s+
匹配任何空白字符(等于[\r\n\t\f\v ]
)+
量词- 在一次和无限次之间匹配,尽可能多次,根据需要回馈(贪婪)
- Global pattern flags
- g modifier: global. All matches (don't return after first match)
- 全局模式标志
- g 修饰符:全局。所有比赛(第一场比赛后不返回)
回答by Michael Berkowski
Have you tried the \s
?
你试过\s
吗?
str.replace(/\s/g, "X");
回答by Headshota
Try this:
尝试这个:
str.replace(/\s/g, "X")
回答by jimver04
Not /gi but /g
不是 /gi 而是 /g
var fname = "My Family File.jpg"
fname = fname.replace(/ /g,"_");
console.log(fname);
gives
给
"My_Family_File.jpg"
回答by GigiProve
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"
回答by Siten
Actually it has been worked but
实际上它已经工作但是
just try this.
试试这个。
take the value /\s/g into a string variable like
将值 /\s/g 放入字符串变量中,例如
String a = /\s/g;
str = str.replaceAll(a,"X");
回答by dude
I've used the "slugify" method from underscore.string and it worked like a charm:
我使用了 underscore.string 中的“slugify”方法,它的作用就像一个魅力:
https://github.com/epeli/underscore.string#slugifystring--string
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.
很酷的是,你真的可以只导入这个方法,不需要导入整个库。