我有这些字符串:
var a = ".-. - --. .. - . .-. .. .";
var x = "";
我想替换:
".-." with "r"
"-" with "t"
"--." with "g"
".." with "i"
"." with "e"
并将值存储在变量x上,因此新字符串应变为:
x = "r t g i t e r i e";
我试过这个但是不起作用:
var a = ".-. - --. .. - . .-. .. .";
var x = "";
//first of all, words with 3 characters
x = a.replace(/.-./g, "r");
x = x.replace(/--./g, "g");
//then words with 2 characters
x = x.replace(/../g, "i");
//finally words with 1 character
x = x.replace(/-/g, "t");
x = x.replace(/./g, "e");
document.write(x);
x成为“eeeeeeee”为什么?怎么修? 谢谢大家
答案 0 :(得分:2)
答案 1 :(得分:1)
您需要转发.
\.
var a = ".-. - --. .. - . .-. .. .";
var x = "";
//first of all, words with 3 characters
x = a.replace(/\.-\./g, "r");
console.log(x);
x = x.replace(/--./g, "g");
console.log(x);
//then words with 2 characters
x = x.replace(/\.\./g, "i");
console.log(x);
//finally words with 1 character
x = x.replace(/-/g, "t");
console.log(x);
x = x.replace(/\./g, "e");
console.log(x);
document.write(x);