用数组元素替换字符串

时间:2017-08-26 16:58:01

标签: javascript ecmascript-6

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

我想将string替换为namearray的元素,以便字符串变为'My name is Peter Parker'

以下是解决此问题的方法 -

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

但这并没有像预期的那样发挥作用。

7 个答案:

答案 0 :(得分: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 :(得分: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);




答案 2 :(得分:1)

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

答案 3 :(得分: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);

答案 4 :(得分:0)

  1. output是一个局部变量,只是声明它是没用的。
  2. replace(String, String)只会替换第一个匹配的模式。
  3. 这是我的解决方案:

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

答案 5 :(得分: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}`;

答案 6 :(得分:0)

string.match(/\[~\w+\]/g).forEach((item,index)=>{
  string = string.replace(item, nameArray [index])
})

您可以根据需要使用上述代码