我正在尝试从 HTML 字符串中替换图像名称 (product-1-placeholder-href.png)。我尝试正确使用所有正则表达式规则。但是,它仍然不匹配并替换字符串,我真的不知道为什么。
所以这是我的正则表达式:
var myStr = htmlContent;
var newStr = myStr.replace(/'product-1-placeholder-href\.png'/g, 'SOMETHINGIMPORTANT');
console.log(newStr.indexOf('product-1-placeholder-href.png'));
console.log(newStr.indexOf('SOMETHINGIMPORTANT'));
第一个 console.log 仍然给我一个索引,第二个是“-1”所以没有匹配。
这是我要替换的 HTML 部分:
<div id="Group_9">
<svg class="Rectangle">
<rect id="Rectangle" rx="0" ry="0" x="0" y="0" width="44" height="44">
</rect>
</svg>
<svg class="ID43059702_02_B">
<pattern elementId="ID43059702_02_B_A2_Rectangle_31" id="product-1-placeholder" x="0" y="0" width="100%" height="100%">
<image id="product-image-1" x="0" y="0" width="100%" height="100%"
href="product-1-placeholder-href.png"
xlink:href="product-1-placeholder-href.png" alt="No image found">
</image>
</pattern>
</svg>
</div>
我的正则表达式是错误的还是无法在这个 HTML 字符串中替换?
最佳答案
您不能在正则表达式中使用引号来指定字符串值。 通过删除引号尝试以下方式。
var myStr = "<html><body>product-1-placeholder-href\.png</body></html>";
var newStr = myStr.replace(/product-1-placeholder-href\.png/g, 'SOMETHINGIMPORTANT');
console.log(newStr);
关于Javascript:用html字符串中的正则表达式替换图像名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56168674/