Template literal inside of the RegEx

混江龙づ霸主 提交于 2019-11-26 11:39:14

问题


I tried to place a template literal inside of a RegEx, and it didn\'t work. I then made a variable regex which holds my RegEx, but it still not giving me the desired result.

However if I console.log(regex) individually, I do receive the desired RegEx, such as /.+?(?=location)/i, /.+?(?=date)/i and so on, but once I place regex inside the .replace it appears not to be working

function validate (data) {
  let testArr = Object.keys(data);
  errorMessages.forEach((elem, i) => {
    const regex = `/.+?(?=${elem.value})/i`;
    const a = testArr[i].replace(regex, \'\');
    })
  }

回答1:


Your regex variable is a String. To make it a RegExp, use

const regex = new RegExp(`.+?(?=${elemvalue.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')})`, "i"); 

Also, it is a good idea to escape the variable part in the regex so as all special regex metacharacters were treated as literals.

const s = "final (location)";
const elemvalue = "(location)";
const regex = new RegExp(`.+?(?=${elemvalue.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')})`, "i");
// console.log(regex); // /.+?(?=\(location\))/i
// console.log(typeof(regex)); // object
let a = s.replace(regex, '');
console.log(a);


来源:https://stackoverflow.com/questions/43390873/template-literal-inside-of-the-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!