我需要在\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
答案 0 :(得分:0)
您可以尝试以下方法:
var str = 'Jhony Jhons,jhon@gmail.com,380967574366';
var regex = /,[0-9]+/g;
str.replace(regex, '\n');
上面的代码段可能会输出您想要的内容,即Jhony Jhons,jhon@gmail.com\n
答案 1 :(得分:0)
有很多方法可以做到,而且非常简单,因此请尝试以下简单答案:-
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
答案 2 :(得分:0)
您需要一个正则表达式来选择完整的电话号码以及前面的逗号。您当前的正则表达式选择每个数字,并用“ \ 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
答案 3 :(得分:0)
var str = "Jhony Jhons,jhon@gmail.com,380967574366";
var result = str.replace(/,\d+/g,'\\n');
console.log(result)