Skip to content


JavaScript String.replace with regex

I often use String.replace in JavaScript whenever I have to use JavaScript. Today was the day that I ended up with using it for my work. I know that String.replace supports regular expression to match your string, but I was not clear if I could use “capturing groups” and “quantifiers”. As I guessed, I was able to use quantifiers in the replace string like the sample below:

    var link_template = '<ol>\
        <li><label>Link 1 Title:</label><input class="text" id="relLink1title" name="relLink{1}title" value="" /></li>\
        <li><label>Link 1 URL:</label><input class="text" id="relLink1url" name="relLink{1}url" value="" /></li>\
        <li><label>Link 1 Img URL:</label><input class="text" id="rellink1imgurl" name="rellink{1}imgurl" value="" /></li>\
        <li class="btn"><span><a href="#" class="new-related-link">Add a New Link</a> | <a href="#" class="remove-related-link">Remove</a></span></li>\
        </ol>';
 
    link_template = link_template.replace(/(<label>.*?)(\d)(.*?<\/label>)/im, '$1 2 $2');

Posted in Frontend Tech, Programming, Tips. Tagged with , , , .

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.