Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 字符串插值。查找与[…]内的字符串匹配的对象属性,并替换为属性值_Javascript_Regex_Function_Object - Fatal编程技术网

Javascript 字符串插值。查找与[…]内的字符串匹配的对象属性,并替换为属性值

Javascript 字符串插值。查找与[…]内的字符串匹配的对象属性,并替换为属性值,javascript,regex,function,object,Javascript,Regex,Function,Object,我正在处理一个函数,该函数查找与[…]中的字符串匹配的objects prop,并替换为prop的值。。它还必须忽略[…]内部的任何字符串,并删除外部方括号 比如说 插入('Hello[name][[author]',{name:'foo',author:'bar'}) 将导致“Hello foo[作者]” 这是到目前为止我的代码 const person1 = { name: 'John', author: 'John & John'}; const person2 = { name:

我正在处理一个函数,该函数查找与[…]中的字符串匹配的objects prop,并替换为prop的值。。它还必须忽略[…]内部的任何字符串,并删除外部方括号

比如说

插入('Hello[name][[author]',{name:'foo',author:'bar'})

将导致“Hello foo[作者]”

这是到目前为止我的代码

const person1 = { name: 'John', author: 'John & John'};
const person2 = { name: 'Jill', author: 'Jk Jowling' };
const person3 = { name: 'Jack', author: 'Wacko Jacko'};

const str1 = 'Hello [name] [[author]]';

// Find the objects prop that matches the string inside [...] and replace with the value of the prop
// Ignore the values inside double brackets [[...]]


const interpolate = (string, obj) => {
// Throw errors if incorrect arguments are passed in
if (!string || typeof string !== 'string') {
    throw new Error(`"string" is required`);
}

if (!obj || typeof obj !== 'object') {
    throw new Error(`"object" is required`);
}

Object.keys(obj).map((value) => {
    string
    .split(' ')
    .indexOf(`[${value}]`) === 1 || string.indexOf(`[[${value}]]`) === -1
  ? console.log(string.replaceAll(`[${value}]`, obj[value])) 
  : console.log(`One or more unidentifiers found in String: ${string}`)
})


// Working better but still need to work on conditionals

// Removed RegEx

// Used replaceAll to target multiple [string]


};

interpolate(str1, person1);
interpolate(str1, person2);
interpolate(str1, person3);

你可以用正则表达式

(?<!\[)\[([^[\]]*)](?!\])