Javascript Regex转换字符串



我不熟悉Javascript Regex。谁能告诉我如何转换字符串像"Minus162Plus140"变成"-162,140"或" plus162 - minus140 "进入"162、-140";用match还是replace?提前感谢!

在前面答案的基础上,您还需要处理其他情况,如" plus162 " minus140 ":

text = "Minus162Plus140";
text = text.replace(/^Minus/, "-");   // Handle when Minus comes first
text = text.replace("Minus", ",-");   // And second
text = text.replace(/^Plus/, "");     // Handle when Plus comes first
text = text.replace(/Plus/, ",");     // And second

但是这种方法本身是脆弱的,并且假设字符串总是/^(Minus|Plus)d+(Minus|Plus)d+$/的形式,您可以先用正则表达式验证:

if (/^(Minus|Plus)d+(Minus|Plus)d+$/) {
... do the replacement
} else {
... handle the error
}

你可以直接使用字符串替换:

text = "Minus162Plus140";
text = text.replace("Minus", ",-");
text = text.replace("Plus", ",+");
console.log(text);

或正则表达式:

text = "Minus162Plus140";
re = /Plus/;
text = text.replace(re, ',+');
re = /Minus/;
text = text.replace(re, ',-');
// Then to remove the initial comma:
re = /^,/;
text = text.replace(re, '');
console.log(text);

最新更新