簡體   English   中英

我怎樣才能從我的字符串中刪除特定字符?

[英]How can i trim just specific characters from my string?

我有以下數組

const re = '    ';
var arr  = ['\t', '\n3\t3', '\n\t', '\n3\t3', '\n2\t', '\n\t2', '\n']

我需要從字符串中刪除 \t 和 \n 字符。 所以當我嘗試

for(let i = 0;i < arr.length;i++) {
let row = arr[i].split(re);
console.log(row);
}

我明白了

['', '']
['\n3', '3']
['\n', '']
['\n3', '3']
['\n2', '']
['\n', '2']
['\n']

當我到達這一點時,我找不到在這里刪除 \n 字符的方法,所以當我只有\n作為元素時,它應該被替換為 '' - 空字符串。

例如,如果角色內部包含其他東西

\n2

所以 \n 在數字之前或之后然后我應該只得到數字並且里面只有 2

我怎樣才能替換這個 \n 字符

使用replace() function 的字符串結合map() function 的數組。 它看起來像這樣

arr.map(c => c.replace(/(\n|\t)/gi, ''))

Output 將是:

[ '', '33', '', '33', '2', '2', '' ]

如果您不想在數組中看到空字符串,您可以使用 .filter(Boolean) 過濾它們

arr.map(c => c.replace(/(\n|\t)/gi, '')).filter(Boolean)

Output 將是:

[ '33', '33', '2', '2' ]

參考: 這里

使用 split 方法不是好的做法。 您可以改用替換方法。

這是您要執行的操作的示例:

 var someText = "Here's some text.\n It has some line breaks that will be removed \r using Javascript.\r\n"; someText = someText.replace(/(\r\n|\n|\r)/gm,""); console.log(someText);

您可以編輯要在其中使用的替換方法。

注意:“/(\r\n|\n|\r)/gm”這是一個正則表達式。

您可以對[\t\n]+進行正則表達式替換以刪除這些字符:

 var arr = ['\t', '\n3\t3', '\n\t', '\n3\t3', '\n2\t', '\n\t2', '\n']; var output = arr.map(x => x.replace(/[\t\n]+/g, "")); console.log(output);

請注意,如果您還想刪除其他空白字符,只需對\s+進行正則表達式替換。

你可以只使用String.prototype.trim() 它也清除\n\t 它僅用於修剪。 它不會刪除字符串中間的字符。 例子:

const arr = ['\t', '\n3\t3', '\n\t', '\n3\t3', '\n2\t', '\n\t2', '\n'];
const newArr = arr.map(val => val.trim());

您可以使用簡單的替換 function:

 var arr = ['\t', '\n3\t3', '\n\t', '\n3\t3', '\n2\t', '\n\t2', '\n'] var row=""; var newArr=[]; for(i=0; i<arr.length; i++){ row = parseInt(arr[i].replace('\tn',"")); if(isNaN(row) === false){newArr.push(row)} } console.log(newArr);

首先replace("\,t,n")你的字符,然后parseInt()將剩余的字符串數字轉換為整數,最后區分這些數字並將它們push()到一個新數組。

const re = ' ';                                                       
var arr  = ['\t','\n3\t3','\n\t','\n3\t3','\n2\t','\n\t2','\n']   
 
for(let i=0 ; i< arr.length ; i++) 
{                                                                         
    let row = arr[i].replaceAll('\t','').replaceAll('\n','').split(re);
    console.log(row);
}

暫無
暫無

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

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