我想在JavaScript中替换所有出现的空格字符(空格,制表符,换行符) 怎么办?
我试过了:
str.replace(/ /gi, "X")
答案 0 :(得分:261)
您需要\s
匹配单个空格 字符,包括空格,制表符,表格 饲料,换行。
相当于
[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
Firefox中的和IE中的[ \f\n\r\t\v]
。
str = str.replace(/\s/g, "X");
答案 1 :(得分:27)
\s
是一个涵盖所有空白区域的元字符。你不需要使它不区分大小写 - 白色空间没有大小写。
str.replace(/\s/g, "X")
答案 2 :(得分:12)
如果我们想要用单个字符更改所有多个连接的空格,我们也可以使用它:
str.replace(/\s+/g,'X');
答案 3 :(得分:8)
您是否尝试过\s
?
str.replace(/\s/g, "X");
答案 4 :(得分:4)
试试这个:
str.replace(/\s/gi, "X")
编辑(没有拼写错误的正确版本):
str.replace(/\s/g, "X")
答案 5 :(得分:1)
实际上它已经奏效但
试试吧。
将值/ \ s / g取为字符串变量,如
String a = /\s/g;
str = str.replaceAll(a,"X");
答案 6 :(得分:1)
不是/ gi而是/ g
var fname = "My Family File.jpg"
fname = fname.replace(/ /g,"_");
console.log(fname);
给出
"My_Family_File.jpg"
答案 7 :(得分:1)
如果您使用
str.replace(/\s/g, "");
它将替换所有空格。例如:
var str = "hello my world";
str.replace(/\s/g, "") //the result will be "hellomyworld"
答案 8 :(得分:1)
您可以使用函数trim
let str = ' Hello World ';
alert (str.trim());
Hello World周围的所有前部和后部空间将被删除。
答案 9 :(得分:0)
我使用了underscore.string中的“slugify”方法,它就像一个魅力:
https://github.com/epeli/underscore.string#slugifystring--string
很酷的是你可以真正导入这个方法,不需要导入整个库。