Replace string keys with array elements [on hold]

问题: i have the below code: const chaine = 'lorem {{name}} lorem lorem {{name}}..." ; i need replace all {{name}} with the array elements like this cont list = ['java...

问题:

i have the below code:

const chaine  =  'lorem {{name}} lorem lorem {{name}}..." ;

i need replace all {{name}} with the array elements like this

cont list  = ['java', 'regex']  

so the expected result is

lorem java lorem lorem regex...

Note:

  • {{name}} numbers in string is variable
  • array element length is variable , we can have 1..N

thanks


回答1:

You could look for the replacement values and get the item from list.

var string = 'lorem {{name}} lorem lorem {{name}}...',
    list = ['java', 'regex'],
    result = string.replace(/{{name}}/g, (i => _ => list[i++])(0));

console.log(result);

A bit more advanced version by taking an object and a property for every propery for the index.

var string = 'lorem {{name}} lorem lorem {{name}}, {{foo}}...',
    replacements = { name: ['java', 'regex'], foo: ['bar'] },
    result = string.replace(/{{([^}]+)}}/g, (_, key) => {
        if (!(key in replacements)) return key;
        replacements['_' + key] = replacements['_' + key] || 0;
        return replacements[key][replacements['_' + key]++];
    });

console.log(result);


回答2:

You can make it work using .replace(). Demo:

const chaine  =  "lorem {{name}} lorem lorem {{name}}..." ;
const list  = ['java', 'regex'];
var result = chaine.replace(/{{name}}/g, function(text) {
  return list.shift();
});
console.log(result);


回答3:

const chaine = 'lorem {{name}} lorem lorem {{name}}...';
const list = ['java', 'regex'];

const textWithEverythingReplaced = list.reduce((textWithReplacedValues, wordToReplaceItWith) => {
  return textWithReplacedValues.replace("{{name}}", wordToReplaceItWith)
}, chaine);

console.log(textWithEverythingReplaced);


Disclaimer

As much as this code can work, the algorithm is not robust. It will break when you have more {{name}} than you have replacers.

Unless you can validate the fact that there are equal number of {{name}} as there are list.length, you should be alright.


回答4:

Seen as you want it to be generic, it might also make sense to make into a re-usable function. Below is an example.

const repFn = (str, arr) => {
  let i = 0;
  return str.replace(/{{name}}/g, x =>arr[i ++]);
}

const chaine  =  "lorem {{name}} lorem lorem {{name}}..." ;
const list  = ['java', 'regex'];



console.log(repFn(chaine, list));
console.log(
  repFn("{{name}}, a few {{name}} can {{name}} up the {{name}} of a thousand",
    ["Sometimes", "words", "sum", "wisdom"]
));

  • 发表于 2019-07-07 04:53
  • 阅读 ( 132 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除