2017-10-13 47 views
2

我有這些字符串:替換字符串中的類似的話

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」爲什麼?怎麼修? 謝謝大家

回答

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); 
2

.regular expression匹配任何字符(除了一些特殊字符)。

要專門匹配.字符,使用\.,例如:

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