簡體   English   中英

如何用空字符替換數字

[英]How to replace numbers with an empty char

我需要在\\n新行中替換字符串中的電話號碼。 我的字符串: Jhony Jhons,jhon@gmail.com,380967574366

我嘗試了這個:

var str = 'Jhony Jhons,jhon@gmail.com,380967574366'
var regex = /[0-9]/g;
var rec = str.trim().replace(regex, '\n').split(','); //Jhony Jhons,jhon@gmail.com,

\\n上的數字替換,但是在使用電子郵件后,字符串中需要使用多余的逗號將其刪除。

最后,我的字符串應如下所示:

Jhony Jhons,jhon@gmail.com\n

您可以嘗試以下方法:

var str = 'Jhony Jhons,jhon@gmail.com,380967574366';
var regex = /,[0-9]+/g;
str.replace(regex, '\n');

上面的代碼片段可能會輸出您想要的內容,即Jhony Jhons,jhon@gmail.com\\n

有很多方法可以做到,而且非常簡單,因此請嘗試以下簡單答案:-

var str = 'Jhony Jhons,jhon@gmail.com,380967574366';
var splitted = str.split(",");      //split them by comma
splitted.pop();                     //removes the last element
var rec = splitted.join() + '\n';   //join them

您需要一個正則表達式來選擇完整的電話號碼以及前面的逗號。 您當前的正則表達式選擇每個數字,並用“ \\ n”替換每個數字,結果結果是很多“ \\ n”。 另外,正則表達式與逗號不匹配。

使用以下正則表達式:

var str = 'Jhony Jhons,jhon@gmail.com,380967574366'
var regex = /,[0-9]+$/; 
// it replaces all consecutive digits with the condition at least one digit exists (the "[0-9]+" part) 
// placed at the end of the string (the "$" part) 
// and also the digits must be preceded by a comma (the "," part in the beginning); 
// also no need for global flag (/g) because of the $ symbol (the end of the string) which can be matched only once
var rec = str.trim().replace(regex, '\n'); //the result will be this string: Jhony Jhons,jhon@gmail.com\n

 var str = "Jhony Jhons,jhon@gmail.com,380967574366"; var result = str.replace(/,\\d+/g,'\\\\n'); console.log(result) 

暫無
暫無

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

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