68

javascriptthis contains spaces を使用すると、どのような機能になり ますか?this contains spaces

同様のSOの質問を使用して、次のことを試しましたが、これを機能させることができませんでした。

var string = " this contains   spaces ";

newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
newString = string.replace(/ +/g,'');  //"thiscontainsspaces"

これを達成するための単純な純粋なJavaScriptの方法はありますか?

4

11 に答える 11

161

あなたは近くにいます。

は、見つかったテキストを 2 番目の引数にreplace 置き換えることに注意してください。そう:

newString = string.replace(/\s+/g,''); // "thiscontainsspaces"

任意の数の連続したスペースを見つけて削除します。代わりに単一のスペースに置き換えてみてください!

newString = string.replace(/\s+/g,' ').trim();
于 2013-06-07T01:04:55.173 に答える
25
string.replace(/\s+/g, ' ').trim()
于 2013-06-07T01:04:28.483 に答える
8

私は1つの方法を考え出しましたが、より良い方法があれば興味があります...

string.replace(/\s+/g,' ').trim()
于 2013-06-07T01:04:29.547 に答える