簡體   English   中英

JS:如何僅從字符串內部刪除空格

[英]JS: How to remove white spaces only from inside of string

我只需要用javascript語言從字符串內部刪除空格。 左右兩側可以有該空格。 我沒有找到解決方案...

也許是一些本機功能? 還是含蓄的正則表達式?

我只有:

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

但是它也消除了側面的空白。

我想要:

var str = "   s dasd   asd sad sa d   ";
str = str.replace(/\s+/g, '');
// output
"   sdasdasdsadsad   ";

您可以匹配並捕獲前導/后綴空格,並使用反向引用恢復結果,並刪除所有其他空格。

 var str = " some text "; str = str.replace(/(^\\s+|\\s+$)|\\s+/g, '$1'); console.log("'",str,"'"); 

圖案細節

  • (^\\s+|\\s+$) -組1捕獲一個或多個空格1)在字符串的開頭( ^\\s+ )或2)在字符串的結尾( \\s+$
  • | - 要么
  • \\s+ -字符串中其他任何位置的1+個空格。

$1是對捕獲組內容的反向引用,該捕獲組內容將重新插入到結果字符串中。

為了支持  也可以使用交替(?:\\s| )

 console.log("  s dasd   asd sad sa d  ".replace(/(^(?:\\s| )+|(?:\\s| )+$)|(?:\\s| )+/g, '$1')); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM