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:47

using a regular expression with the replace function does the trick:

string.replace(/\s/g, "")
查看更多
不流泪的眼
3楼-- · 2019-01-02 17:51

Here's a non-regex solution (just for fun):

var s = ' a   b   word word. word, wordword word   ';

// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"

// or ES6:
s = s.split(' ').filter(n => n).join(' '); 
console.log(s); // "a b word word. word, wordword word"

It splits the string by it's whitespaces, remove them all from the array, and joins all the words again, with a single whitespace in between them.

查看更多
忆尘夕之涩
4楼-- · 2019-01-02 17:53

If you want to restrict user to give blank space in the name just create a if statement and give the condition. like I did:

$j('#fragment_key').bind({
    keypress: function(e){
        var key = e.keyCode;
    var character = String.fromCharCode(key); 
    if(character.match( /[' ']/)) {
        alert("Blank space is not allowed in the Name");
        return false;
        }
    }
});
  • create a JQuery function .
  • this is key press event.
  • Initialize a variable.
  • Give condition to match the character
  • show a alert message for your matched condition.
查看更多
春风洒进眼中
5楼-- · 2019-01-02 17:54
姐姐魅力值爆表
6楼-- · 2019-01-02 17:57

var x = " Test Test Test ".split(" ").join(""); alert(x);

查看更多
登录 后发表回答