2017-08-22 73 views
2

說,我有一個字符串使用數組元素進行搜索並使用javascript替換全部?

'I am abc1, my age is abc2 and I live in abc3, abc1' 

和數組,它看起來像

我試圖做一個搜索和替換所有使用在陣列中的每個元素的字符串下面時尚

replace abc1 by xyz1, abc2 by xyz2 etc.. 

即腳本運行後輸出字符串將

I am xyz1, my age is xyz2 and I live in xyz3, xyz1 

這是我試過到目前爲止

var myString = 'I am abc1, my age is abc2 and I live in abc3, abc1'; 
var myArray = ['abc1/xyx1', 'abc2/xyx2', 'abc3/xyx3']; 
for (var i=0; i<=myArray.length; i++){ 
var a1 = myArray[i]; 
var xs = a1.split("/"); 
var new1=xs[0]; 
var new2=xs[1]; 
var replaced = myString.replace(/new1/g, new2); 
} 
document.write(replaced); 

但它無法正常工作。任何人都可以幫忙嗎?

+0

一件事來解決,我想是,<=應<。不過還有更多需要解決的問題。 –

回答

2

基本上你一環太多,採取i < myArray.length和你需要的變量,正則表達式的值。

你可以使用一個構造函數,並建立一個新的正則表達式對象。

最後,你需要更換相同的字符串,並分配到相同的字符串,否則你雖更換,但是你只有上次更換回來。

var myString = 'I am abc1, my age is abc2 and I live in abc3, abc1', 
 
    myArray = ['abc1/xyx1', 'abc2/xyx2', 'abc3/xyx3'], 
 
    i, xs, new1, new2; 
 

 
for (i = 0; i < myArray.length; i++) { 
 
    xs = myArray[i].split("/"); 
 
    new1 = xs[0]; 
 
    new2 = xs[1]; 
 
    myString = myString.replace(new RegExp(new1, 'g'), new2); 
 
} 
 

 
console.log(myString);

+0

我還沒有看到你在一段時間內使用'for'循環。無論如何。 – PeterMader

1

試試這種方法。

首先拆分keys/values並得到一個新的數組(keyValue),它包含舊的和新的單詞。然後我遍歷keyValue並用它的值替換text

var text = 'I am abc1, my age is abc2 and I live in abc3, abc1'; 
 
var words = ['abc1/xyx1', 'abc2/xyx2', 'abc3/xyx3']; 
 

 
var keyValue = words.map(item => { 
 
    var arr = item.split('/'); 
 
    return [arr[0], arr[1]]; 
 
}); 
 

 
keyValue.forEach(item => { 
 
    text = text.replace(new RegExp(item[0], 'g'), item[1]); 
 
}); 
 

 
console.log(text);

+0

你能不介意解釋你的方法,我是JavaScript的新手,所以不明白你的方法, –

0

您可以在words陣列usign String.prototype.forEach(),並在每個循環迭代拆分元素wString.prototype.split()與你需要創建一個常規的兩個索引元素創建一個數組變量a表達和呼叫String.prototype.replace()

var text = 'I am abc1, my age is abc2 and I live in abc3, abc1'; 
 
var words = ['abc1/xyx1', 'abc2/xyx2', 'abc3/xyx3']; 
 

 
words.forEach(function (w) { 
 
    var a = w.split('/'); 
 
    text = text.replace(new RegExp(a[0], 'g'), a[1]); 
 
}); 
 

 
console.log(text);

0

一種功能性的方法:

var text = 'I am abc1, my age is abc2 and I live in abc3, abc1'; 
 
var words = ['abc1/xyx1', 'abc2/xyx2', 'abc3/xyx3']; 
 

 
var result = words.reduce((text, word) => { 
 
    var [ oldWord, newWord ] = word.split('/'); 
 
    return text.replace(new RegExp(oldWord, 'g'), newWord); 
 
}, text); 
 

 
console.log(result);