[英]Special character causing issues with JS replacement
I have this code: 我有以下代码:
var fileData = '<div name="test1"><h1>Test Div 1</h1></div><!-- Start: FindMe --><div name="findme"></div><!-- End: FindMe -->';
var findInDom = "<!-- Start: FindMe -->.*?<!-- End: FindMe -->";
var result = fileData.replace(findInDom, "");
console.log(result);
I'm trying to find everything from and including: 我试图从中找到一切,包括:
<!-- Start: FindMe -->
and 和
<!-- End: FindMe -->
But this code below is not replacing eveything from <!-- Start: FindMe -->
to <!-- End: FindMe -->
so I'm guessing it's a special character issue with -->
causing issues maybe? 但是下面的这段代码并不能代替<!-- Start: FindMe -->
FindMe- <!-- Start: FindMe -->
到<!-- End: FindMe -->
FindMe- <!-- Start: FindMe -->
传送,所以我猜想它是-->
的特殊字符问题,可能引起问题吗?
My HTML: 我的HTML:
<div name="test1"><h1>Test Div 1</h1></div><!-- Start: FindMe --><div name="findme"></div><!-- End: FindMe -->
My Regex/replace: 我的正则表达式/替换:
var findInDom = "<!-- Start: FindMe -->.*?<!-- End: FindMe -->";
My Regex with variable: 我的正则表达式变量:
var findInDom = /<!-- Start: " + name + " -->.*?<!-- End: " + name + " -->/;
--- name being a variable. --- name是一个变量。
Any ideas why this is not replacing? 有什么想法为什么不能取代?
findInDom
is a string, but you're treating it like a regular expression. findInDom
是一个字符串,但是您将其findInDom
正则表达式。
Instead, you want to use a regular expression like so: 相反,您想使用如下正则表达式:
var findInDom = /<!-- Start: FindMe -->.*?<!-- End: FindMe -->/;
If you want to insert the values of variables into your regex, use the regex constructor instead: 如果要将变量的值插入到正则表达式中,请改用regex构造函数:
var name = "FindMe";
var findInDom = "<!-- Start: " + name + " -->.*?<!-- End: " + name + " -->";
var regex = new RegExp(findInDom);
var result = fileData.replace(regex);
You are using String to replace. 您正在使用String进行替换。 Try fileData.replace(new RegExp(findInDom, 'g'),"")
尝试fileData.replace(new RegExp(findInDom, 'g'),"")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.