繁体   English   中英

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

[英]How to replace occurrences of a string by elements of an array in 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?"];

我要实现的目标是用array元素替换每次出现的{question} ,尊重索引,并保留括号。 结果字符串应如下所示:

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

我的想法是,可以通过replacesplit and join来实现它,但是我无法使其正常工作。 任何想法?

 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表示多个匹配项。 并且还接受生成替换函数的函数 ; 我在这里使用了箭头功能

请注意, 在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 

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

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}

您只需在字符串上设置一会儿条件,看看它是否包含{question}。 如果存在并且数组索引存在,则用该数组中的子句替换该子句。

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

 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('')); 

这是执行此操作的函数。 只要数组中有相应的索引,它将替换{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}"));

您可以先将string转换为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);
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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM