Reputation: 1235
I am trying to replace an image name (product-1-placeholder-href.png) from an HTML string. I tried to use all the regex rules correctly. However, it still does not match and replace the string and I really don't know why.
So this is my regex:
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'));
The first console.log still gives me an index, the second one is "-1" so no match.
This is the part of the HTML which I want to replace:
<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>
Is my regex wrong or is it just not possible to replace inside this HTML string?
Upvotes: 1
Views: 295
Reputation: 551
You can not use quotes in regex for specifying string value. Try the following way, by removing quotes.
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);
Upvotes: 1
Reputation: 1471
Why you don't use DOM for this case.
I think it is easy to control and understand
document.getElementById("product-image-1").href="SOMETHINGIMPORTANT";
document.getElementById("product-image-1").setAttribute("xlink:href", "SOMETHINGIMPORTANT");
Thanks for reading.
Upvotes: 1