[英]How to replace characters in string with values from array?
我有兩個數組。
var a = ['one', 'two', 'three'];
var b = ['two', 'three', 'four'];
var string = 'The only one and two and three';
我試着用for-loop。
for ( var i = 0; i < string.length; i++) {
string = string.replace(a[0], b[0]);
string = string.replace(a[1], b[1]);
string = string.replace(a[2], b[2]);
}
但問題是,在第一次迭代后,替換值再次替換! 我想更換one
有兩個 , two
三和three
四 。
預期結果: The only two and three and four
我得到: The only four and four and four
一種可能的方法:
var dict = {};
a.forEach(function(el, i) {
dict[el] = b[i];
});
var patt = a.join('|');
var res = string.replace(new RegExp(patt, 'g'), function(word) {
return dict[word];
});
console.log(res); // The only two and three and four
演示 。 它實際上非常簡單:首先你創建一個字典(其中鍵是要替換的單詞,值是,以及替換它們的單詞),其次,你創建一個'交替'正則表達式(帶|
符號 - 你需要引用元字符,如果有的話)。 最后,使用這個創建的模式進行單個replace
的字符串 - 以及替換函數,該函數在字典中查找特定的“校正字”。
您不需要循環,只需向后替換:
var a = ['one', 'two', 'three'];
var b = ['two', 'three', 'four'];
var string = 'The only one and two and three';
string = string.replace(a[2], b[2]);
string = string.replace(a[1], b[1]);
string = string.replace(a[0], b[0]);
注意:這適用於此示例,它不是通用的。
只是發布一個替代方法,它拆分原始字符串並將其替換為dict對象。
dict對象是在替換之前構建的,因為知道要替換的內容是必不可少的。
var a = ['one', 'two', 'three'];
var b = ['two', 'three', 'four'];
var string = 'The only one and two and three';
var dict = {};
for (var i = 0; i < a.length; i++) {
dict[a[i]] = b[i];
}
var stringtokens = string.split(' ');
for (var i = 0; i < stringtokens.length; i++) {
if (dict.hasOwnProperty(stringtokens[i])){
stringtokens[i] = dict[stringtokens[i]];
}
}
console.log(stringtokens.join(' '));
向后做:
var a = ['one', 'two', 'three'];
var b = ['two', 'three', 'four'];
var string = 'The only one and two and three';
for (var i = string.length-1; i >= 0; i--) {
string = string.replace(a[i], b[i]);
}
您可以反轉每個數組來實現此目的。 另一種方式是常規模式。
此外,您的代碼沒有任何意義。 如果需要迭代數組,為什么要遍歷字符串?
這可行:
for ( var i = 0; i < a.length; i++) {
string = string.replace(a[a.length - 1 - i], b[b.length - 1 - i]);
}
另外,看看這種通用的方式: http : //phpjs.org/functions/str_replace/
你可以這樣做:
str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
此函數可以將數組作為參數。
只是反過來做。 問題是,你替換后one
與two
,更換所有的two
與three
,然后你做同樣的事情用three
和four
,讓你將所有four
時結束。 如果你顛倒了替換的順序,那就不會發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.