Javascript:用html字符串中的正则表达式替换图像名称

标签 javascript regex

我正在尝试从 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/

相关文章:

Javascript - 从对象数组中获取下一个字母

Python REGEX 如何从变量中提取特定数字

java - ReplaceAll 与 ReplaceFirst 的行为差异

javascript - 调用(this.dragger)不起作用,d3.drag()

javascript - 如何修复或解决 iPhone 上的亚像素处理问题?

javascript - 选择类中的所有元素,但不选择当前目标

php - preg_replace : add number after backreference

javascript - 如何覆盖 'border:none' 以克服 Safari 选择错误?

python - 使用正则表达式从文件中获取测试详细信息

javascript - 使用 Regex JS 删除字符串中的重复单词