替换字符串中的类似单词

时间:2017-10-13 17:17:33

标签: javascript text replace

我有这些字符串:

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”为什么?怎么修? 谢谢大家

2 个答案:

答案 0 :(得分:2)

regular expression中的

.匹配任何字符(某些特殊字符除外)。

要专门匹配.字符,请使用\.,例如:

x = x.replace(/\./g, "e");

答案 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);