如何在javascript中用数组元素替换字符串的出现?

时间:2018-03-07 04:56:45

标签: javascript

我有一个模板字符串:

const template = "Answer to {question} must be {YES} and answer to {question} must be {4}";

和一系列值:

const array = ["Is it late?", "What time is it?"];

我想要实现的是将{question}的每个匹配项替换为array的元素,尊重索引,并保留大括号。结果字符串应如下所示:

"Answer to {Is it late?} must be {YES} and answer to {What time is it} must be {4}"

我认为可以通过replacesplitjoin实现这一目标,但我无法让它发挥作用。有什么想法吗?

6 个答案:

答案 0 :(得分:3)

const template_string = "Answer to {question} must be {YES} and for {question} it's {4}";
const things = ["Is it late?", "What time is it?"]; // This is to be empty.
const result = template_string.replace(/(?<={)question(?=})/mg, _ => things.shift());
console.log(things); // Been empty
console.log(result);

String.prototype.replace()支持匹配事物的正则表达式。您可以使用lookbehind和lookahead匹配括号内的question;和m用于多行支持,g用于多个匹配。并且它还接受生成替换的函数;我在这里使用arrow function

请注意,regular expression lookbehind assertion in Javascript 第4阶段的提案 ;它需要相当现代的引擎(Chrome 62+支持它。)。如果这困扰你,那么外观是可选的;你可以用以下代替。

const result = template_string.replace(/\{question\}/mg, _ => `{${things.shift()}}`);

对你而言,我给你容易选择的。

const template_string = "Answer to {question} must be {YES} and for {question} it's {4}";
const things = ["Is it late?", "What time is it?"];

function go_with_lookbehind(template_string, things)
{
	const the_things = Array.from(things);
	const result = template_string.replace(
		/(?<={)question(?=})/mg,
		_ => the_things.shift()
	);
	return result;
}

function go_without_lookbehind_but_a_template_literal(template_string, things)
{
	const the_things = Array.from(things);
	const result = template_string.replace(
		/\{question\}/mg,
		_ => `{${the_things.shift()}}`
	);
	return result;
}

function go_without_lookbehind_and_a_template_literal(template_string, things)
{
	const the_things = Array.from(things);
	const result = template_string.replace(
		/\{question\}/mg,
		_ => ('{' + the_things.shift() + '}')
	);
	return result;
}

console.info(go_with_lookbehind(template_string, things));
console.info(go_without_lookbehind_but_a_template_literal(template_string, things));
console.info(go_without_lookbehind_and_a_template_literal(template_string, things));

console.info("template_string: ", template_string); // Unchanged
console.info("things: ", things); // Unchanged

答案 1 :(得分:2)

可能更简单的解决方案是:

let counter = 0
const template = "Answer to {question} must be {YES} and answer to {question} must be {4}";
const array = ["Is it late?", "What time is it?"];

let temp = template

// we are checking two things here
// 1. Whether the string contains the {question} or not
// 2. Whether the array index exists or not

while (temp.includes('{question}') && typeof array[counter] !== 'undefined') {
temp = temp.replace('{question}', `{${array[counter]}}`);
counter++;
}

console.log(temp);

//Answer to {Is it late?} must be {YES} and answer to {What time is it?} must be {4}

你可以在字符串上设置一个while条件,看它是否包含{question}。如果它存在且数组索引存在,则将该子句替换为数组中的子句。

额外的检查是为了处理异常。如果您确定{question}的实例数与数组中的元素数相同,那么您可以删除检查。

答案 2 :(得分:1)

&#13;
&#13;
const template = 'Answer to {question} must be {YES} and answer to {question} must be {4}';
const questions = ['Is it late?', 'What time is it?'];

document.write(template.split('{question}').map((chunk, index) => `${chunk}${index < questions.length ? `{${questions[index]}}` : ''}`).join(''));
&#13;
&#13;
&#13;

答案 3 :(得分:0)

这是一个执行此操作的功能。只要数组中有相应的索引

,它就会替换{question}
    function replaceCurlies(str,arr,seprator){
      var temp_arr=str.split(seprator);
      var ret=[];
      for(var i=0;i<temp_arr.length;i++){
        if(i<arr.length)
          ret.push(temp_arr[i]+"{"+arr[i]+"}")
        else
          ret.push(temp_arr[i])
      }
      return ret.join()
    }

    const array = ["Is it late?", "What time is it?"];
    const template = "Answer to {question} must be {YES} and answer to {question} must be {4}";
    console.log(replaceCurlies(template,array,"{question}"));

答案 4 :(得分:0)

您可以先将string转换为array of string,然后将其传递给map并转换所需的地点,然后将array of string重新转换为string

const array = ["Is it late?", "What time is it?"];
const template = "Answer to {question} must be {YES} and answer to {question} must be {4}";
let arr = template.split(' ');
let i=0;
arr = arr.map(value=>{
  if(value==='{question}')
    {
      value = `{${array[i]}}`;
      i++;
    }
    else
      value = value
  return value
});
arr = arr.join(' ');
console.log(arr);

答案 5 :(得分:0)

function merge(left,right) {
  var result = [];
  var index = 0;
  var length = left.length;

  while (index < length) {
     result.push(left[index]);
     if(right[index]){ //since array lenghts are not equal
       result.push(right[index]);
     }

     index++;
  }
  return result;
}

const template = "Answer to {question} must be {YES} and answer to {question} must be {4}";
const array = ["Is it late?", "What time is it?"];

var arraySplit = template.split("{question}");
var allArray = merge(arraySplit,array);
var resStr =  allArray.join();