2017-08-26 187 views
3
let string = 'My name is [~FIRSTNAME] [~LASTNAME]'; 
let nameArray = ['Peter', 'Parker']; 
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]'] 

我想更換stringnamearray使帶子變得'My name is Peter Parker'用數組元素替換字符串

下面的元素是我的方法解決這個問題 -

patternToBeReplaced.forEach(function (match, index) { 
     var output = string.replace(match, nameArray[index]); 
}); 

但是,這是不按預期工作。

+2

你需要更新字符串變量....但讓塊級範圍......所以用箭頭函數來代替 –

+0

是,' string = string.replace(...' – James

+0

嘗試使用'reduce'而不是'forEach' – Bergi

回答

4

你可以使用Array#reduce和使用字符串下一個替代品。

let string = 'My name is [~FIRSTNAME] [~LASTNAME]'; 
 
let nameArray = ['Peter', 'Parker']; 
 
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]'] 
 

 
string = patternToBeReplaced.reduce((s, m, i) => s.replace(m, nameArray[i]), string); 
 

 
console.log(string);

1
patternToBeReplaced.forEach(function (match, index) { 
    string = string.replace(match, nameArray[index]); 
}); 
2

您正在創建字符串模板系統。由於您已經使用ECAMScript 6語法,因此您可以使用新的內置模板文字。

let [FIRSTNAME, LASTNAME] = ['Peter', 'Parker']; 
 
let string = `My name is ${FIRSTNAME} ${LASTNAME}`; 
 

 
console.log(string);


這也將工作當有字符串中的給定標籤的多個插入更乾淨。

let [FIRSTNAME, LASTNAME] = ['Peter', 'Parker']; 
 
let string = `My name is ${LASTNAME}... ${FIRSTNAME} ${LASTNAME}`; 
 

 
console.log(string);

0

類似的東西。

let str = 'My name is [~FIRSTNAME] [~LASTNAME]'; 
 
let nameArray = ['Peter', 'Parker']; 
 
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]'] 
 

 

 
const result = patternToBeReplaced.reduce((str, placeholder, i) => { 
 
return str.replace(placeholder, nameArray[i]); 
 
}, str); 
 
console.log(result);

0
  1. output是一個局部變量,這是沒用的,只是宣稱它。
  2. replace(String, String)只會替換第一個匹配的模式。

這裏是我的解決方案:

let replaceWithArrayElements = (patterns, replacements, targetString) => { 
    patterns.forEach((pattern, i) => targetString = targetString.replace(new RegExp(pattern, 'g'))); 
    return targetString; 
} 
0

首先解決方案,讓您的基本代碼:

let string = 'My name is [~FIRSTNAME] [~LASTNAME]'; 
let nameArray = ['Peter', 'Parker']; 
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]']; 
patternToBeReplaced 
.forEach((match, i)=>{ 
    string = string 
      .replace(match, nameArray[i]); 
}); 

使用Map

let string = 'My name is [~FIRSTNAME] [~LASTNAME]'; 
let replaceMap = new Map(); 
replaceMap.set('[~FIRSTNAME]', 'Peter'); 
replaceMap.set('[~LASTNAME]', 'Parker'); 
replaceMap.forEach((key, value)=>{ 
    string = string.replace(key, value); 
}); 

使用ES6 「模板」 字符串:

/* 
*Have some ways of getting the first name in "firstName" 
*Have some ways of getting the last name in "lastName" 
*/ 
let string = `My name is ${firstName} ${lastName}`; 
0
string.match(/\[~\w+\]/g).forEach((item,index)=>{ 
    string = string.replace(item, nameArray [index]) 
}) 

您可以使用上面的代碼你需要

相關問題