簡體   English   中英

jQuery刪除文本中的空格

[英]Jquery remove spaces in text

我有一些代碼可以從字符串中獲取某些文本,但是我希望輸出中沒有空格。 我試過把.replace(' ', ''); 我在代碼的某些部分,但是它總是使代碼無法運行

這是下面使用的代碼,它將輸出this text但我希望它輸出thistext

<div id="text"></div>

var text ='blah blah text-name="this text"';

const gettext = text;
const gettextoutput = [];
const re = /text-name="([^"]+)"/g;
let match;
while ((match = re.exec(gettext)) !== null) {
  gettextoutput.push(match[1]);

}

$("#text").append(gettextoutput);

由於要將匹配項分配給數組,因此必須替換該數組所有元素的空格,否則JavaScript將拋出錯誤,因為Arrays沒有replace方法。

 var text ='blah blah text-name="this text"'; const gettext = text; const gettextoutput = []; const re = /text-name="([^"]+)"/g; let match; while ((match = re.exec(gettext)) !== null) { gettextoutput.push(match[1]); } $("#text").append(gettextoutput.map(e => e.replace(" ", ""))); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="text"></div> 

伙計,您可以使用香草javascript來做到這一點:

'text with spaces'.split(' ').join('')

另外,您的初始代碼采用了正確的方法。 嘗試這個:

'text with spaces'.replace(/\\s/g, '')

暫無
暫無

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

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