我想在JavaScript中替换所有出现的空格字符(空格,制表符,换行符)。 怎么办?
我试过了:
str.replace(/ /gi, "X")
\s
是一个涵盖所有白色空间的元字符。你不需要使它不区分大小写 - 白色空间没有大小写。
str.replace(/\s/g, "X")
如果我们想要用单个字符更改所有多个连接的空格,我们也可以使用它:
str.replace(/\s+/g,'X');
你试过\s
吗?
str.replace(/\s/g, "X");
试试这个:
str.replace(/\s/gi, "X")
编辑(没有拼写错误的正确版本):
str.replace(/\s/g, "X")
实际上它已经奏效了
试试吧。
将值/ \ s / g转换为字符串变量,如
String a = /\s/g;
str = str.replaceAll(a,"X");
不是/ gi而是/ g
var fname = "My Family File.jpg"
fname = fname.replace(/ /g,"_");
console.log(fname);
给
"My_Family_File.jpg"
如果你使用
str.replace(/\s/g, "");
它取代了所有的空格。例如:
var str = "hello my world";
str.replace(/\s/g, "") //the result will be "hellomyworld"
我使用了underscore.string中的“slugify”方法,它就像一个魅力:
https://github.com/epeli/underscore.string#slugifystring--string
很酷的是你可以真正导入这个方法,不需要导入整个库。