Replace multiple whitespaces with single whitespac

2019-01-02 17:18发布

I have strings with extra whitespaces, each time there's more than only one whitespace I'd like it be only one.

Anyone? I tried searching google, but nothing worked for me.

Thanks

11条回答
孤独寂梦人
2楼-- · 2019-01-02 17:38

I presume you're looking to strip spaces from the beginning and/or end of the string (rather than removing all spaces?

If that's the case, you'll need a regex like this:

mystring = mystring.replace(/(^\s+|\s+$)/g,' ');

This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:

mystring = mystring.replace(/\s+$/g,' ');

Hope that helps.

查看更多
十年一品温如言
3楼-- · 2019-01-02 17:41

You can augment String to implement these behaviors as methods, as in:

String.prototype.killWhiteSpace = function() {
    return this.replace(/\s/g, '');
};

String.prototype.reduceWhiteSpace = function() {
    return this.replace(/\s+/g, ' ');
};

This now enables you to use the following elegant forms to produce the strings you want:

"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra        whitespaces".reduceWhiteSpace();
查看更多
倾城一夜雪
4楼-- · 2019-01-02 17:42

Something like this:

s.replace(/\s+/g, ' ');
查看更多
步步皆殇っ
5楼-- · 2019-01-02 17:42

I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:

  • I want to replace multiple occurences of whitespace inside the string with a single space
  • ...and... I do not want whitespaces in the beginnin or end of the string (trim)

For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):

s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');

The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.

查看更多
笑指拈花
6楼-- · 2019-01-02 17:43

Try this.

var string = "         string             1";
string = string.trim().replace(/\s+/g, ' ');

the result will be

string 1

What happened here is that it will trim the outside spaces first using trim() then trim the inside spaces using .replace(/\s+/g, ' ').

查看更多
浅入江南
7楼-- · 2019-01-02 17:45

How about this one?

"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')

outputs "my test string with crazy stuff is cool "

This one gets rid of any tabs as well

查看更多
登录 后发表回答