用数组替换字符串

时间:2019-10-02 17:01:56

标签: javascript

我有一些字符串,在处理(翻译)之前必须将其替换,然后在处理(翻译完成)之后再次将其替换。

 var str = 'BUY [[Manufacturer]] [[Name]] cheap or get other [[Categories]] from [[Storename]] <i class="fa fa-check"></i> Thousands of satisfied customers.';

所以我首先在数组中引用它们:

var res = str.match(/\[\[.*?\]\]/gm);

然后我替换它们:

var placeholder_string = str.replace(/\[\[.*?\]\]/gm,"|");

然后将对其进行处理(在本例中为翻译)。

现在,我要回退所有占位符“ |”数组res

我知道我可以在replace()的replace参数中使用一个函数,但是请帮助我如何有效地实现该功能。

var revert_string = placeholder_string.replace("|", myfunc());

还是有更好的方法?

3 个答案:

答案 0 :(得分:1)

一个简单的解决方案是像您建议的那样使用函数替换,对于每个匹配项,从保存的匹配项中检索(并删除)下一项。

Array.shift()很好地做到了这一点,您无需跟踪索引或其他任何内容。

const str = 'BUY [[Manufacturer]] [[Name]] cheap or get other [[Categories]] from [[Storename]] <i class="fa fa-check"></i> Thousands of satisfied customers.';

const res = str.match(/\[\[.*?\]\]/gm);

// for demonstration purposes,
// uppercase the placeholder to show that the string has changed
// while maintaining the fields' positions afterwards
const placeholder_string = str.replace(/\[\[.*?\]\]/gm, "|").toUpperCase();

const revert_string = placeholder_string.replace(/\|/g, () => {
  return res.shift();
});

console.log(revert_string);

答案 1 :(得分:1)

我建议您使用split,这也可以使您在文本中使用|。这种方法也可能更快(我认为应该这样)。

const str = '||BUY|| [[Manufacturer]] [[Name]] cheap or get other [[Categories]] from [[Storename]] <i class="fa fa-check"></i> Thousands of satisfied customers.';

// | here does not match the | character, its an or statement. So match "[[" or "]]"
const parts = str.split(/\[\[|\]\]/g) 
//get every odd part, so everything between "[[" and "]]"
let placeholders = parts.filter((_,i) => i%2==1)

//process, just as an example. Put your translation logic here
placeholders = placeholders.map((t, i) => `(Replacement for ${t})`)

//put them back together
const replaced = parts.map((p, i) => {
  if(i % 2 == 1) return placeholders[(i-1)/2];
  return p
});

const replacedStr = replaced.join('')

console.log(replacedStr)

答案 2 :(得分:1)

您可以使用计数器,并在每次替换回调调用时增加计数器

var str = 'BUY [[Manufacturer]] [[Name]] cheap or get other [[Categories]] from [[Storename]] <i class="fa fa-check"></i> Thousands of satisfied customers.';

var res = str.match(/\[\[.*?\]\]/gm)

var placeholder_string = str.replace(/\[\[.*?\]\]/gm,"|").toLowerCase()


function stringRevert(str){
  let i = 0;
  return str.replace(/\|/g,()=> res[i++]);
}

var revert_string = stringRevert(placeholder_string)

console.log(revert_string)

相关问题