Replace all whitespace characters

回眸只為那壹抹淺笑 提交于 2019-11-26 18:54:43

问题


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")

回答1:


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");



回答2:


\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")



回答3:


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

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



回答4:


Have you tried the \s?

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



回答5:


Try this:

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



回答6:


Not /gi but /g

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

gives

"My_Family_File.jpg"



回答7:


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"



回答8:


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");



回答9:


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.



来源:https://stackoverflow.com/questions/6507056/replace-all-whitespace-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!