如何从javascript文件中获取价值并更新正则表达式中的新值?

时间:2015-01-25 06:19:41

标签: javascript regex

我有从工作区读取的javascript文件 这是javascript的一部分

 "/*!
 * ${copyright}
 */

 .......


           a.initLibrary({
                            a: "a",
                            b: "b",
                            cattr: ["val1","val2"],

            });
      ...

我想为cattr参数添加新值

   var pattern = [\s\S]*?cattr\s*:\s*\[([\s\S]*?)\]/;
    var controlStr = oContent.match(pattern);
   var controlArr = controlStr[1].trim().replace(/"/g, "").split(",");
   var newInput = "val3"
  if ( controlArr[0] !== "" ){
        newInput += ",";
    }
    newInput += "\t";
    oContent = oContent.replace("cattr: [",newInput );

我可以用正则表达式完成所有操作吗?有一种情况,cattr可能是空的,没有任何价值含义

          cattr :[]

我如何使用正则表达式而不是字符串逻辑?

1 个答案:

答案 0 :(得分:0)

如果你仍然希望使用纯正则表达式。你可以试试这个。

let orig1 = `a.initLibrary({
                            a: "a",
                            b: "b",
                            cattr: ["val1","val2"],

            });`;
            
let orig2 = `a.initLibrary({
                            a: "a",
                            b: "b",
                            cattr: [],

            });`;            
            
const replaceFn = (match, capture1) => {
  let insertValue = "adsdas";
  if(capture1 === "]") return `cattr: ["${insertValue}"]`;
  return `cattr: ["${insertValue}",`;
}

let new1 = orig1.replace(/cattr:\s*\[\s*(\])?/, replaceFn);
let new2 = orig2.replace(/cattr:\s*\[\s*(\])?/, replaceFn);

console.log(new1);
console.log(new2);