Get number of times regex .replace() occurs












1















I'm building an html linter, and first thing I am trying to do is remove all of the alt attributes. I'm using a regex to replace alt tags. Is there a way to get the number alt codes removed.



If you paste:




alt="23432" one two three alt='12312' four five six alt = "1124412"




You should get one two three four five six, and I would like to store 3 into a variable called numReplaced.






function removeAlts(input) {
var textIn = document.getElementById("textIn").value;
var regex = /alts*=s*["'][a-zA-z0-9s]*["']/ig;
var textOut = textIn.replace(regex, '');
document.getElementById("textIn").value = textOut;
//var numReplaced = ????
}

<button class="btn" onclick="removeAlts()">Remove Alts</button>
<div class="title">
<h3>Paste code in box below and press button to remove alts!</h3>
</div>
<textarea name="input" id="textIn" cols="60" rows=15"></textarea>












share|improve this question

























  • You need to take into account cases like alt="it's okay"

    – Ahmad
    Nov 22 '18 at 5:30
















1















I'm building an html linter, and first thing I am trying to do is remove all of the alt attributes. I'm using a regex to replace alt tags. Is there a way to get the number alt codes removed.



If you paste:




alt="23432" one two three alt='12312' four five six alt = "1124412"




You should get one two three four five six, and I would like to store 3 into a variable called numReplaced.






function removeAlts(input) {
var textIn = document.getElementById("textIn").value;
var regex = /alts*=s*["'][a-zA-z0-9s]*["']/ig;
var textOut = textIn.replace(regex, '');
document.getElementById("textIn").value = textOut;
//var numReplaced = ????
}

<button class="btn" onclick="removeAlts()">Remove Alts</button>
<div class="title">
<h3>Paste code in box below and press button to remove alts!</h3>
</div>
<textarea name="input" id="textIn" cols="60" rows=15"></textarea>












share|improve this question

























  • You need to take into account cases like alt="it's okay"

    – Ahmad
    Nov 22 '18 at 5:30














1












1








1








I'm building an html linter, and first thing I am trying to do is remove all of the alt attributes. I'm using a regex to replace alt tags. Is there a way to get the number alt codes removed.



If you paste:




alt="23432" one two three alt='12312' four five six alt = "1124412"




You should get one two three four five six, and I would like to store 3 into a variable called numReplaced.






function removeAlts(input) {
var textIn = document.getElementById("textIn").value;
var regex = /alts*=s*["'][a-zA-z0-9s]*["']/ig;
var textOut = textIn.replace(regex, '');
document.getElementById("textIn").value = textOut;
//var numReplaced = ????
}

<button class="btn" onclick="removeAlts()">Remove Alts</button>
<div class="title">
<h3>Paste code in box below and press button to remove alts!</h3>
</div>
<textarea name="input" id="textIn" cols="60" rows=15"></textarea>












share|improve this question
















I'm building an html linter, and first thing I am trying to do is remove all of the alt attributes. I'm using a regex to replace alt tags. Is there a way to get the number alt codes removed.



If you paste:




alt="23432" one two three alt='12312' four five six alt = "1124412"




You should get one two three four five six, and I would like to store 3 into a variable called numReplaced.






function removeAlts(input) {
var textIn = document.getElementById("textIn").value;
var regex = /alts*=s*["'][a-zA-z0-9s]*["']/ig;
var textOut = textIn.replace(regex, '');
document.getElementById("textIn").value = textOut;
//var numReplaced = ????
}

<button class="btn" onclick="removeAlts()">Remove Alts</button>
<div class="title">
<h3>Paste code in box below and press button to remove alts!</h3>
</div>
<textarea name="input" id="textIn" cols="60" rows=15"></textarea>








function removeAlts(input) {
var textIn = document.getElementById("textIn").value;
var regex = /alts*=s*["'][a-zA-z0-9s]*["']/ig;
var textOut = textIn.replace(regex, '');
document.getElementById("textIn").value = textOut;
//var numReplaced = ????
}

<button class="btn" onclick="removeAlts()">Remove Alts</button>
<div class="title">
<h3>Paste code in box below and press button to remove alts!</h3>
</div>
<textarea name="input" id="textIn" cols="60" rows=15"></textarea>





function removeAlts(input) {
var textIn = document.getElementById("textIn").value;
var regex = /alts*=s*["'][a-zA-z0-9s]*["']/ig;
var textOut = textIn.replace(regex, '');
document.getElementById("textIn").value = textOut;
//var numReplaced = ????
}

<button class="btn" onclick="removeAlts()">Remove Alts</button>
<div class="title">
<h3>Paste code in box below and press button to remove alts!</h3>
</div>
<textarea name="input" id="textIn" cols="60" rows=15"></textarea>






javascript html regex






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 5:23







dvdktn

















asked Nov 22 '18 at 5:21









dvdktndvdktn

287




287













  • You need to take into account cases like alt="it's okay"

    – Ahmad
    Nov 22 '18 at 5:30



















  • You need to take into account cases like alt="it's okay"

    – Ahmad
    Nov 22 '18 at 5:30

















You need to take into account cases like alt="it's okay"

– Ahmad
Nov 22 '18 at 5:30





You need to take into account cases like alt="it's okay"

– Ahmad
Nov 22 '18 at 5:30












2 Answers
2






active

oldest

votes


















1














One option would be to use a replacer function, and increment a counter every time it's called. You should also fix your regex to capture the initial double or single quote in the alt attribute, so that it can be matched later with a backreference. With this backreference strategy, you'll also be able to match alts with quotes in them, so add "' to the character set.



In addition, you can use the i flag instead of repeating [a-zA-Z, and d instead of 0-9. Also, quotes do not need to be escaped in regular expression literals.






function removeAlts(input) {
var textIn = document.getElementById("textIn").value;
var regex = /s*alts*=s*(["'])[a-zds"']*?1/ig;
let counter = 0;
var textOut = textIn.replace(regex, () => {
counter++;
return '';
});
document.getElementById("textIn").value = textOut;
console.log(counter);
}

<button class="btn" onclick="removeAlts()">Remove Alts</button>
<div class="title">
<h3>Paste code in box below and press button to remove alts!</h3>
</div>
<textarea name="input" id="textIn" cols="60" rows="15">
<tag alt="foo"></tag>
<tag alt="bar"></tag>
<tag alt="that's okay"></tag>
</textarea>





But it would be far more elegant to use DOMParser to search for everything with an alt attribute, and remove them






function removeAlts(input) {
var textIn = document.getElementById("textIn").value;
const doc = new DOMParser().parseFromString(textIn, 'text/html');
const alts = doc.querySelectorAll('[alt]');
console.log(alts.length);
alts.forEach(elm => elm.removeAttribute('alt'));
document.getElementById("textIn").value = doc.body.innerHTML;
}

<button class="btn" onclick="removeAlts()">Remove Alts</button>
<div class="title">
<h3>Paste code in box below and press button to remove alts!</h3>
</div>
<textarea name="input" id="textIn" cols="60" rows="15">
<tag alt="foo"></tag>
<tag alt="bar"></tag>
<tag alt="that's okay"></tag>
</textarea>








share|improve this answer


























  • Your regex will not work properly in cases like alt="that's okay" since it contains double quotes and single quotes

    – Ahmad
    Nov 22 '18 at 5:26













  • Yep, need to fix OP's regex to capture that character and backreference it later

    – CertainPerformance
    Nov 22 '18 at 5:29











  • Thanks! I never knew about DOMParser :)

    – dvdktn
    Nov 22 '18 at 5:36



















0














You may use same quote in the end of your pattern like this:
/alts*=s*(["']).+1/ig






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424338%2fget-number-of-times-regex-replace-occurs%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    One option would be to use a replacer function, and increment a counter every time it's called. You should also fix your regex to capture the initial double or single quote in the alt attribute, so that it can be matched later with a backreference. With this backreference strategy, you'll also be able to match alts with quotes in them, so add "' to the character set.



    In addition, you can use the i flag instead of repeating [a-zA-Z, and d instead of 0-9. Also, quotes do not need to be escaped in regular expression literals.






    function removeAlts(input) {
    var textIn = document.getElementById("textIn").value;
    var regex = /s*alts*=s*(["'])[a-zds"']*?1/ig;
    let counter = 0;
    var textOut = textIn.replace(regex, () => {
    counter++;
    return '';
    });
    document.getElementById("textIn").value = textOut;
    console.log(counter);
    }

    <button class="btn" onclick="removeAlts()">Remove Alts</button>
    <div class="title">
    <h3>Paste code in box below and press button to remove alts!</h3>
    </div>
    <textarea name="input" id="textIn" cols="60" rows="15">
    <tag alt="foo"></tag>
    <tag alt="bar"></tag>
    <tag alt="that's okay"></tag>
    </textarea>





    But it would be far more elegant to use DOMParser to search for everything with an alt attribute, and remove them






    function removeAlts(input) {
    var textIn = document.getElementById("textIn").value;
    const doc = new DOMParser().parseFromString(textIn, 'text/html');
    const alts = doc.querySelectorAll('[alt]');
    console.log(alts.length);
    alts.forEach(elm => elm.removeAttribute('alt'));
    document.getElementById("textIn").value = doc.body.innerHTML;
    }

    <button class="btn" onclick="removeAlts()">Remove Alts</button>
    <div class="title">
    <h3>Paste code in box below and press button to remove alts!</h3>
    </div>
    <textarea name="input" id="textIn" cols="60" rows="15">
    <tag alt="foo"></tag>
    <tag alt="bar"></tag>
    <tag alt="that's okay"></tag>
    </textarea>








    share|improve this answer


























    • Your regex will not work properly in cases like alt="that's okay" since it contains double quotes and single quotes

      – Ahmad
      Nov 22 '18 at 5:26













    • Yep, need to fix OP's regex to capture that character and backreference it later

      – CertainPerformance
      Nov 22 '18 at 5:29











    • Thanks! I never knew about DOMParser :)

      – dvdktn
      Nov 22 '18 at 5:36
















    1














    One option would be to use a replacer function, and increment a counter every time it's called. You should also fix your regex to capture the initial double or single quote in the alt attribute, so that it can be matched later with a backreference. With this backreference strategy, you'll also be able to match alts with quotes in them, so add "' to the character set.



    In addition, you can use the i flag instead of repeating [a-zA-Z, and d instead of 0-9. Also, quotes do not need to be escaped in regular expression literals.






    function removeAlts(input) {
    var textIn = document.getElementById("textIn").value;
    var regex = /s*alts*=s*(["'])[a-zds"']*?1/ig;
    let counter = 0;
    var textOut = textIn.replace(regex, () => {
    counter++;
    return '';
    });
    document.getElementById("textIn").value = textOut;
    console.log(counter);
    }

    <button class="btn" onclick="removeAlts()">Remove Alts</button>
    <div class="title">
    <h3>Paste code in box below and press button to remove alts!</h3>
    </div>
    <textarea name="input" id="textIn" cols="60" rows="15">
    <tag alt="foo"></tag>
    <tag alt="bar"></tag>
    <tag alt="that's okay"></tag>
    </textarea>





    But it would be far more elegant to use DOMParser to search for everything with an alt attribute, and remove them






    function removeAlts(input) {
    var textIn = document.getElementById("textIn").value;
    const doc = new DOMParser().parseFromString(textIn, 'text/html');
    const alts = doc.querySelectorAll('[alt]');
    console.log(alts.length);
    alts.forEach(elm => elm.removeAttribute('alt'));
    document.getElementById("textIn").value = doc.body.innerHTML;
    }

    <button class="btn" onclick="removeAlts()">Remove Alts</button>
    <div class="title">
    <h3>Paste code in box below and press button to remove alts!</h3>
    </div>
    <textarea name="input" id="textIn" cols="60" rows="15">
    <tag alt="foo"></tag>
    <tag alt="bar"></tag>
    <tag alt="that's okay"></tag>
    </textarea>








    share|improve this answer


























    • Your regex will not work properly in cases like alt="that's okay" since it contains double quotes and single quotes

      – Ahmad
      Nov 22 '18 at 5:26













    • Yep, need to fix OP's regex to capture that character and backreference it later

      – CertainPerformance
      Nov 22 '18 at 5:29











    • Thanks! I never knew about DOMParser :)

      – dvdktn
      Nov 22 '18 at 5:36














    1












    1








    1







    One option would be to use a replacer function, and increment a counter every time it's called. You should also fix your regex to capture the initial double or single quote in the alt attribute, so that it can be matched later with a backreference. With this backreference strategy, you'll also be able to match alts with quotes in them, so add "' to the character set.



    In addition, you can use the i flag instead of repeating [a-zA-Z, and d instead of 0-9. Also, quotes do not need to be escaped in regular expression literals.






    function removeAlts(input) {
    var textIn = document.getElementById("textIn").value;
    var regex = /s*alts*=s*(["'])[a-zds"']*?1/ig;
    let counter = 0;
    var textOut = textIn.replace(regex, () => {
    counter++;
    return '';
    });
    document.getElementById("textIn").value = textOut;
    console.log(counter);
    }

    <button class="btn" onclick="removeAlts()">Remove Alts</button>
    <div class="title">
    <h3>Paste code in box below and press button to remove alts!</h3>
    </div>
    <textarea name="input" id="textIn" cols="60" rows="15">
    <tag alt="foo"></tag>
    <tag alt="bar"></tag>
    <tag alt="that's okay"></tag>
    </textarea>





    But it would be far more elegant to use DOMParser to search for everything with an alt attribute, and remove them






    function removeAlts(input) {
    var textIn = document.getElementById("textIn").value;
    const doc = new DOMParser().parseFromString(textIn, 'text/html');
    const alts = doc.querySelectorAll('[alt]');
    console.log(alts.length);
    alts.forEach(elm => elm.removeAttribute('alt'));
    document.getElementById("textIn").value = doc.body.innerHTML;
    }

    <button class="btn" onclick="removeAlts()">Remove Alts</button>
    <div class="title">
    <h3>Paste code in box below and press button to remove alts!</h3>
    </div>
    <textarea name="input" id="textIn" cols="60" rows="15">
    <tag alt="foo"></tag>
    <tag alt="bar"></tag>
    <tag alt="that's okay"></tag>
    </textarea>








    share|improve this answer















    One option would be to use a replacer function, and increment a counter every time it's called. You should also fix your regex to capture the initial double or single quote in the alt attribute, so that it can be matched later with a backreference. With this backreference strategy, you'll also be able to match alts with quotes in them, so add "' to the character set.



    In addition, you can use the i flag instead of repeating [a-zA-Z, and d instead of 0-9. Also, quotes do not need to be escaped in regular expression literals.






    function removeAlts(input) {
    var textIn = document.getElementById("textIn").value;
    var regex = /s*alts*=s*(["'])[a-zds"']*?1/ig;
    let counter = 0;
    var textOut = textIn.replace(regex, () => {
    counter++;
    return '';
    });
    document.getElementById("textIn").value = textOut;
    console.log(counter);
    }

    <button class="btn" onclick="removeAlts()">Remove Alts</button>
    <div class="title">
    <h3>Paste code in box below and press button to remove alts!</h3>
    </div>
    <textarea name="input" id="textIn" cols="60" rows="15">
    <tag alt="foo"></tag>
    <tag alt="bar"></tag>
    <tag alt="that's okay"></tag>
    </textarea>





    But it would be far more elegant to use DOMParser to search for everything with an alt attribute, and remove them






    function removeAlts(input) {
    var textIn = document.getElementById("textIn").value;
    const doc = new DOMParser().parseFromString(textIn, 'text/html');
    const alts = doc.querySelectorAll('[alt]');
    console.log(alts.length);
    alts.forEach(elm => elm.removeAttribute('alt'));
    document.getElementById("textIn").value = doc.body.innerHTML;
    }

    <button class="btn" onclick="removeAlts()">Remove Alts</button>
    <div class="title">
    <h3>Paste code in box below and press button to remove alts!</h3>
    </div>
    <textarea name="input" id="textIn" cols="60" rows="15">
    <tag alt="foo"></tag>
    <tag alt="bar"></tag>
    <tag alt="that's okay"></tag>
    </textarea>








    function removeAlts(input) {
    var textIn = document.getElementById("textIn").value;
    var regex = /s*alts*=s*(["'])[a-zds"']*?1/ig;
    let counter = 0;
    var textOut = textIn.replace(regex, () => {
    counter++;
    return '';
    });
    document.getElementById("textIn").value = textOut;
    console.log(counter);
    }

    <button class="btn" onclick="removeAlts()">Remove Alts</button>
    <div class="title">
    <h3>Paste code in box below and press button to remove alts!</h3>
    </div>
    <textarea name="input" id="textIn" cols="60" rows="15">
    <tag alt="foo"></tag>
    <tag alt="bar"></tag>
    <tag alt="that's okay"></tag>
    </textarea>





    function removeAlts(input) {
    var textIn = document.getElementById("textIn").value;
    var regex = /s*alts*=s*(["'])[a-zds"']*?1/ig;
    let counter = 0;
    var textOut = textIn.replace(regex, () => {
    counter++;
    return '';
    });
    document.getElementById("textIn").value = textOut;
    console.log(counter);
    }

    <button class="btn" onclick="removeAlts()">Remove Alts</button>
    <div class="title">
    <h3>Paste code in box below and press button to remove alts!</h3>
    </div>
    <textarea name="input" id="textIn" cols="60" rows="15">
    <tag alt="foo"></tag>
    <tag alt="bar"></tag>
    <tag alt="that's okay"></tag>
    </textarea>





    function removeAlts(input) {
    var textIn = document.getElementById("textIn").value;
    const doc = new DOMParser().parseFromString(textIn, 'text/html');
    const alts = doc.querySelectorAll('[alt]');
    console.log(alts.length);
    alts.forEach(elm => elm.removeAttribute('alt'));
    document.getElementById("textIn").value = doc.body.innerHTML;
    }

    <button class="btn" onclick="removeAlts()">Remove Alts</button>
    <div class="title">
    <h3>Paste code in box below and press button to remove alts!</h3>
    </div>
    <textarea name="input" id="textIn" cols="60" rows="15">
    <tag alt="foo"></tag>
    <tag alt="bar"></tag>
    <tag alt="that's okay"></tag>
    </textarea>





    function removeAlts(input) {
    var textIn = document.getElementById("textIn").value;
    const doc = new DOMParser().parseFromString(textIn, 'text/html');
    const alts = doc.querySelectorAll('[alt]');
    console.log(alts.length);
    alts.forEach(elm => elm.removeAttribute('alt'));
    document.getElementById("textIn").value = doc.body.innerHTML;
    }

    <button class="btn" onclick="removeAlts()">Remove Alts</button>
    <div class="title">
    <h3>Paste code in box below and press button to remove alts!</h3>
    </div>
    <textarea name="input" id="textIn" cols="60" rows="15">
    <tag alt="foo"></tag>
    <tag alt="bar"></tag>
    <tag alt="that's okay"></tag>
    </textarea>






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 22 '18 at 5:33

























    answered Nov 22 '18 at 5:23









    CertainPerformanceCertainPerformance

    87.3k154774




    87.3k154774













    • Your regex will not work properly in cases like alt="that's okay" since it contains double quotes and single quotes

      – Ahmad
      Nov 22 '18 at 5:26













    • Yep, need to fix OP's regex to capture that character and backreference it later

      – CertainPerformance
      Nov 22 '18 at 5:29











    • Thanks! I never knew about DOMParser :)

      – dvdktn
      Nov 22 '18 at 5:36



















    • Your regex will not work properly in cases like alt="that's okay" since it contains double quotes and single quotes

      – Ahmad
      Nov 22 '18 at 5:26













    • Yep, need to fix OP's regex to capture that character and backreference it later

      – CertainPerformance
      Nov 22 '18 at 5:29











    • Thanks! I never knew about DOMParser :)

      – dvdktn
      Nov 22 '18 at 5:36

















    Your regex will not work properly in cases like alt="that's okay" since it contains double quotes and single quotes

    – Ahmad
    Nov 22 '18 at 5:26







    Your regex will not work properly in cases like alt="that's okay" since it contains double quotes and single quotes

    – Ahmad
    Nov 22 '18 at 5:26















    Yep, need to fix OP's regex to capture that character and backreference it later

    – CertainPerformance
    Nov 22 '18 at 5:29





    Yep, need to fix OP's regex to capture that character and backreference it later

    – CertainPerformance
    Nov 22 '18 at 5:29













    Thanks! I never knew about DOMParser :)

    – dvdktn
    Nov 22 '18 at 5:36





    Thanks! I never knew about DOMParser :)

    – dvdktn
    Nov 22 '18 at 5:36













    0














    You may use same quote in the end of your pattern like this:
    /alts*=s*(["']).+1/ig






    share|improve this answer




























      0














      You may use same quote in the end of your pattern like this:
      /alts*=s*(["']).+1/ig






      share|improve this answer


























        0












        0








        0







        You may use same quote in the end of your pattern like this:
        /alts*=s*(["']).+1/ig






        share|improve this answer













        You may use same quote in the end of your pattern like this:
        /alts*=s*(["']).+1/ig







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 22 '18 at 8:00









        TechnobulkaTechnobulka

        14




        14






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424338%2fget-number-of-times-regex-replace-occurs%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

            Alcedinidae

            RAC Tourist Trophy