I’m having trouble with the replace and replaceAll functions in JavaScript. I have the following fragment, which is part of a Handlebars file:
<div class="default-nav-footer__social-media--responsive">
{{#each socialNetworks}}
<a href="{{url}}" target="_blank" class="header--custom-svg" rel="noopener noreferrer nofollow">
{{> (concat 'icons/social_networks/' (lookup . 'name'))}}
</a>
{{/each}}
</div>
When I try to run:
str.replace('icons/social_networks/', 'icons/');
It doesn’t work. I also tried:
str.replace(new RegExp(`icons/social_networks/`, 'g'), 'icons/');
but that didn’t work either. Interestingly, if I use:
str.replace(new RegExp(`icons/social_networks/`, 'g'), match => {
console.log(match);
});
It successfully logs all the matches it finds in the string, but no matter what I try, the actual string replacement is not happening as expected.
Why is replace not working, even though the matches are being found? How can I ensure that the strings are replaced correctly?
Edit: str
refers to handlebar fragment shown above. I still expect replace
to return a new string with the required replacements, but the result is exactly the same as the original string. We are not compiling the Handlebars template because it doesn’t matter for this case—I am handling it as plain text, not as Handlebars code. I mentioned the Handlebars syntax because it might look different from standard HTML, but that’s not relevant to the problem at hand.
3
<div class="default-nav-footer__social-media--responsive">
{{#each socialNetworks}}
<a href="{{url}}" target="_blank" class="header--custom-svg" rel="noopener noreferrer nofollow">
{{> (concat 'icons/' (lookup . 'name'))}}
</a>
{{/each}}
</div>
const template = Handlebars.compile(yourTemplateString);
const data = { socialNetworks: [{ name: 'facebook', url: 'https://example.com/facebook' }] };
const renderedHtml = template(data);
const replacedHtml = renderedHtml.replace('icons/social_networks/', 'icons/');
1