How to remove leading and trailing white spaces from a given html string?












156















I have the following html string. What would be sample code in JavaScript to remove leading and trailing white spaces from this string?



<p>&nbsp;&nbsp;</p>
<div>&nbsp;</div>
Trimming using JavaScript<br />
<br />
<br />
<br />
all leading and trailing white spaces
<p>&nbsp;&nbsp;</p>
<div>&nbsp;</div>









share|improve this question























  • check this

    – musefan
    Apr 5 '12 at 16:06











  • What is your real problem? Do you want to remove whitespace before inserting nodes in the document?

    – Rob W
    Apr 5 '12 at 16:06











  • I want to remove all leading white spaces as well as all trailing white spaces. Very my like the Trim method in C# except that it removes even white spaces.

    – Sunil
    Apr 5 '12 at 16:17











  • So in my example, I finally should get the following after trimming: Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces

    – Sunil
    Apr 5 '12 at 16:23













  • @Sunil I don't know if you ever solved this, but you could try one of these solutions: stackoverflow.com/questions/16708158/…

    – Chris Baker
    Aug 1 '14 at 0:01
















156















I have the following html string. What would be sample code in JavaScript to remove leading and trailing white spaces from this string?



<p>&nbsp;&nbsp;</p>
<div>&nbsp;</div>
Trimming using JavaScript<br />
<br />
<br />
<br />
all leading and trailing white spaces
<p>&nbsp;&nbsp;</p>
<div>&nbsp;</div>









share|improve this question























  • check this

    – musefan
    Apr 5 '12 at 16:06











  • What is your real problem? Do you want to remove whitespace before inserting nodes in the document?

    – Rob W
    Apr 5 '12 at 16:06











  • I want to remove all leading white spaces as well as all trailing white spaces. Very my like the Trim method in C# except that it removes even white spaces.

    – Sunil
    Apr 5 '12 at 16:17











  • So in my example, I finally should get the following after trimming: Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces

    – Sunil
    Apr 5 '12 at 16:23













  • @Sunil I don't know if you ever solved this, but you could try one of these solutions: stackoverflow.com/questions/16708158/…

    – Chris Baker
    Aug 1 '14 at 0:01














156












156








156


18






I have the following html string. What would be sample code in JavaScript to remove leading and trailing white spaces from this string?



<p>&nbsp;&nbsp;</p>
<div>&nbsp;</div>
Trimming using JavaScript<br />
<br />
<br />
<br />
all leading and trailing white spaces
<p>&nbsp;&nbsp;</p>
<div>&nbsp;</div>









share|improve this question














I have the following html string. What would be sample code in JavaScript to remove leading and trailing white spaces from this string?



<p>&nbsp;&nbsp;</p>
<div>&nbsp;</div>
Trimming using JavaScript<br />
<br />
<br />
<br />
all leading and trailing white spaces
<p>&nbsp;&nbsp;</p>
<div>&nbsp;</div>






javascript removing-whitespace






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Apr 5 '12 at 16:04









SunilSunil

10.1k1877145




10.1k1877145













  • check this

    – musefan
    Apr 5 '12 at 16:06











  • What is your real problem? Do you want to remove whitespace before inserting nodes in the document?

    – Rob W
    Apr 5 '12 at 16:06











  • I want to remove all leading white spaces as well as all trailing white spaces. Very my like the Trim method in C# except that it removes even white spaces.

    – Sunil
    Apr 5 '12 at 16:17











  • So in my example, I finally should get the following after trimming: Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces

    – Sunil
    Apr 5 '12 at 16:23













  • @Sunil I don't know if you ever solved this, but you could try one of these solutions: stackoverflow.com/questions/16708158/…

    – Chris Baker
    Aug 1 '14 at 0:01



















  • check this

    – musefan
    Apr 5 '12 at 16:06











  • What is your real problem? Do you want to remove whitespace before inserting nodes in the document?

    – Rob W
    Apr 5 '12 at 16:06











  • I want to remove all leading white spaces as well as all trailing white spaces. Very my like the Trim method in C# except that it removes even white spaces.

    – Sunil
    Apr 5 '12 at 16:17











  • So in my example, I finally should get the following after trimming: Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces

    – Sunil
    Apr 5 '12 at 16:23













  • @Sunil I don't know if you ever solved this, but you could try one of these solutions: stackoverflow.com/questions/16708158/…

    – Chris Baker
    Aug 1 '14 at 0:01

















check this

– musefan
Apr 5 '12 at 16:06





check this

– musefan
Apr 5 '12 at 16:06













What is your real problem? Do you want to remove whitespace before inserting nodes in the document?

– Rob W
Apr 5 '12 at 16:06





What is your real problem? Do you want to remove whitespace before inserting nodes in the document?

– Rob W
Apr 5 '12 at 16:06













I want to remove all leading white spaces as well as all trailing white spaces. Very my like the Trim method in C# except that it removes even white spaces.

– Sunil
Apr 5 '12 at 16:17





I want to remove all leading white spaces as well as all trailing white spaces. Very my like the Trim method in C# except that it removes even white spaces.

– Sunil
Apr 5 '12 at 16:17













So in my example, I finally should get the following after trimming: Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces

– Sunil
Apr 5 '12 at 16:23







So in my example, I finally should get the following after trimming: Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces

– Sunil
Apr 5 '12 at 16:23















@Sunil I don't know if you ever solved this, but you could try one of these solutions: stackoverflow.com/questions/16708158/…

– Chris Baker
Aug 1 '14 at 0:01





@Sunil I don't know if you ever solved this, but you could try one of these solutions: stackoverflow.com/questions/16708158/…

– Chris Baker
Aug 1 '14 at 0:01












7 Answers
7






active

oldest

votes


















225














See the String method trim() - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim



var myString = '  bunch    of <br> string data with<p>trailing</p> and leading space   ';
myString = myString.trim();
// or myString = String.trim(myString);


Edit



As noted in other comments, it is possible to use the regex approach. The trim method is effectively just an alias for a regex:



if(!String.prototype.trim) {  
String.prototype.trim = function () {
return this.replace(/^s+|s+$/g,'');
};
}


... this will inject the method into the native prototype for those browsers who are still swimming in the shallow end of the pool.






share|improve this answer



















  • 3





    I would prefer a regex way, becaase it isn't supported in all browsers (cough cough IE < 9).

    – PeeHaa
    Apr 5 '12 at 16:07








  • 1





    Trim method will not trim white spaces, but only spaces. So its not what I am looking for.

    – Sunil
    Apr 5 '12 at 16:20






  • 7





    I'm not sure what you think "white spaces" are, but trim will remove whitespace in general (newline, space, tab etc), not just the space character.

    – bsa
    Sep 2 '13 at 6:14






  • 2





    @bsa I came to understand he means "white space" in the visual sense, as in "visually blank areas in the results of rendering the HTML", and then he added in a comment above "except newlines caused by br tags".

    – Chris Baker
    Sep 3 '13 at 15:45








  • 2





    why is there not a check mark on an answer with 170 upvotes? SO confuses me sometimes.

    – tcoulson
    Feb 20 '18 at 20:39



















58














var str = "  my awesome string   "
str.trim();


for old browsers, use regex



str = str.replace(/^[ ]+|[ ]+$/g,'')
//str = "my awesome string"





share|improve this answer





















  • 2





    "[ ]" is exactly the same as " ". A character grouping of exactly one character is.. well... exactly one character.

    – Flimzy
    Mar 14 '15 at 23:40








  • 1





    @Flimzy: Yes, it would make more sense to write [tn ] or just s instead of [ ] which makes no sense.

    – erik
    Aug 11 '15 at 14:31



















11














string.replace(/^s+|s+$/g, "");





share|improve this answer
























  • Read the question, &nbsp; is used instead of an ordinary whitespace. On top of this, the whitespace is contained within a tag.

    – Rob W
    Apr 5 '12 at 16:07






  • 1





    It doesn't do what I need.

    – Sunil
    Apr 5 '12 at 16:16



















6














If you're working with a multiline string, like a code file:



<html>
<title>test</title>
<body>
<h1>test</h1>
</body>
</html>


And want to replace all leading lines, to get this result:



<html>
<title>test</title>
<body>
<h1>test</h1>
</body>
</html>


You must add the multiline flag to your regex, ^ and $ match line by line:



string.replace(/^s+|s+$/gm, '');


Relevant quote from docs:




The "m" flag indicates that a multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string.







share|improve this answer































    4














    I know this is a very old question but it still doesn't have an accepted answer. I see that you want the following removed: html tags that are "empty" and white spaces based on an html string.



    I have come up with a solution based on your comment for the output you are looking for:



    Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces 





    var str = "<p>&nbsp;&nbsp;</p><div>&nbsp;</div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p>&nbsp;&nbsp;</p><div>&nbsp;</div>";
    console.log(str.trim().replace(/&nbsp;/g, '').replace(/<[^/>][^>]*></[^>]+>/g, ""));





    .trim() removes leading and trailing whitespace



    .replace(/&nbsp;/g, '') removes &nbsp;



    .replace(/<[^/>][^>]*></[^>]+>/g, "")); removes empty tags






    share|improve this answer































      3














      var trim = your_string.replace(/^s+|s+$/g, '');





      share|improve this answer



















      • 1





        Will it remove white spaces like <br /> or <p>&nbsp;&nbsp;</p> <div>&nbsp;</div> ? Trmming simple spaces is not a problem. Its the white space removal that I am after.

        – Sunil
        Apr 4 '13 at 0:17











      • will it remove white space

        – user2086641
        Aug 26 '13 at 5:53



















      2














      01). If you need to remove only leading and trailing white space use this:



      var address = "  No.255 Colombo  "
      address.replace(/^[ ]+|[ ]+$/g,'');


      this will return string "No.255 Colombo"



      02). If you need to remove all the white space use this:



      var address = "  No.255 Colombo  "
      address.replace(/s/g,"");


      this will return string "No.255Colombo"






      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%2f10032024%2fhow-to-remove-leading-and-trailing-white-spaces-from-a-given-html-string%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        7 Answers
        7






        active

        oldest

        votes








        7 Answers
        7






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        225














        See the String method trim() - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim



        var myString = '  bunch    of <br> string data with<p>trailing</p> and leading space   ';
        myString = myString.trim();
        // or myString = String.trim(myString);


        Edit



        As noted in other comments, it is possible to use the regex approach. The trim method is effectively just an alias for a regex:



        if(!String.prototype.trim) {  
        String.prototype.trim = function () {
        return this.replace(/^s+|s+$/g,'');
        };
        }


        ... this will inject the method into the native prototype for those browsers who are still swimming in the shallow end of the pool.






        share|improve this answer



















        • 3





          I would prefer a regex way, becaase it isn't supported in all browsers (cough cough IE < 9).

          – PeeHaa
          Apr 5 '12 at 16:07








        • 1





          Trim method will not trim white spaces, but only spaces. So its not what I am looking for.

          – Sunil
          Apr 5 '12 at 16:20






        • 7





          I'm not sure what you think "white spaces" are, but trim will remove whitespace in general (newline, space, tab etc), not just the space character.

          – bsa
          Sep 2 '13 at 6:14






        • 2





          @bsa I came to understand he means "white space" in the visual sense, as in "visually blank areas in the results of rendering the HTML", and then he added in a comment above "except newlines caused by br tags".

          – Chris Baker
          Sep 3 '13 at 15:45








        • 2





          why is there not a check mark on an answer with 170 upvotes? SO confuses me sometimes.

          – tcoulson
          Feb 20 '18 at 20:39
















        225














        See the String method trim() - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim



        var myString = '  bunch    of <br> string data with<p>trailing</p> and leading space   ';
        myString = myString.trim();
        // or myString = String.trim(myString);


        Edit



        As noted in other comments, it is possible to use the regex approach. The trim method is effectively just an alias for a regex:



        if(!String.prototype.trim) {  
        String.prototype.trim = function () {
        return this.replace(/^s+|s+$/g,'');
        };
        }


        ... this will inject the method into the native prototype for those browsers who are still swimming in the shallow end of the pool.






        share|improve this answer



















        • 3





          I would prefer a regex way, becaase it isn't supported in all browsers (cough cough IE < 9).

          – PeeHaa
          Apr 5 '12 at 16:07








        • 1





          Trim method will not trim white spaces, but only spaces. So its not what I am looking for.

          – Sunil
          Apr 5 '12 at 16:20






        • 7





          I'm not sure what you think "white spaces" are, but trim will remove whitespace in general (newline, space, tab etc), not just the space character.

          – bsa
          Sep 2 '13 at 6:14






        • 2





          @bsa I came to understand he means "white space" in the visual sense, as in "visually blank areas in the results of rendering the HTML", and then he added in a comment above "except newlines caused by br tags".

          – Chris Baker
          Sep 3 '13 at 15:45








        • 2





          why is there not a check mark on an answer with 170 upvotes? SO confuses me sometimes.

          – tcoulson
          Feb 20 '18 at 20:39














        225












        225








        225







        See the String method trim() - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim



        var myString = '  bunch    of <br> string data with<p>trailing</p> and leading space   ';
        myString = myString.trim();
        // or myString = String.trim(myString);


        Edit



        As noted in other comments, it is possible to use the regex approach. The trim method is effectively just an alias for a regex:



        if(!String.prototype.trim) {  
        String.prototype.trim = function () {
        return this.replace(/^s+|s+$/g,'');
        };
        }


        ... this will inject the method into the native prototype for those browsers who are still swimming in the shallow end of the pool.






        share|improve this answer













        See the String method trim() - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim



        var myString = '  bunch    of <br> string data with<p>trailing</p> and leading space   ';
        myString = myString.trim();
        // or myString = String.trim(myString);


        Edit



        As noted in other comments, it is possible to use the regex approach. The trim method is effectively just an alias for a regex:



        if(!String.prototype.trim) {  
        String.prototype.trim = function () {
        return this.replace(/^s+|s+$/g,'');
        };
        }


        ... this will inject the method into the native prototype for those browsers who are still swimming in the shallow end of the pool.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Apr 5 '12 at 16:06









        Chris BakerChris Baker

        39.7k976108




        39.7k976108








        • 3





          I would prefer a regex way, becaase it isn't supported in all browsers (cough cough IE < 9).

          – PeeHaa
          Apr 5 '12 at 16:07








        • 1





          Trim method will not trim white spaces, but only spaces. So its not what I am looking for.

          – Sunil
          Apr 5 '12 at 16:20






        • 7





          I'm not sure what you think "white spaces" are, but trim will remove whitespace in general (newline, space, tab etc), not just the space character.

          – bsa
          Sep 2 '13 at 6:14






        • 2





          @bsa I came to understand he means "white space" in the visual sense, as in "visually blank areas in the results of rendering the HTML", and then he added in a comment above "except newlines caused by br tags".

          – Chris Baker
          Sep 3 '13 at 15:45








        • 2





          why is there not a check mark on an answer with 170 upvotes? SO confuses me sometimes.

          – tcoulson
          Feb 20 '18 at 20:39














        • 3





          I would prefer a regex way, becaase it isn't supported in all browsers (cough cough IE < 9).

          – PeeHaa
          Apr 5 '12 at 16:07








        • 1





          Trim method will not trim white spaces, but only spaces. So its not what I am looking for.

          – Sunil
          Apr 5 '12 at 16:20






        • 7





          I'm not sure what you think "white spaces" are, but trim will remove whitespace in general (newline, space, tab etc), not just the space character.

          – bsa
          Sep 2 '13 at 6:14






        • 2





          @bsa I came to understand he means "white space" in the visual sense, as in "visually blank areas in the results of rendering the HTML", and then he added in a comment above "except newlines caused by br tags".

          – Chris Baker
          Sep 3 '13 at 15:45








        • 2





          why is there not a check mark on an answer with 170 upvotes? SO confuses me sometimes.

          – tcoulson
          Feb 20 '18 at 20:39








        3




        3





        I would prefer a regex way, becaase it isn't supported in all browsers (cough cough IE < 9).

        – PeeHaa
        Apr 5 '12 at 16:07







        I would prefer a regex way, becaase it isn't supported in all browsers (cough cough IE < 9).

        – PeeHaa
        Apr 5 '12 at 16:07






        1




        1





        Trim method will not trim white spaces, but only spaces. So its not what I am looking for.

        – Sunil
        Apr 5 '12 at 16:20





        Trim method will not trim white spaces, but only spaces. So its not what I am looking for.

        – Sunil
        Apr 5 '12 at 16:20




        7




        7





        I'm not sure what you think "white spaces" are, but trim will remove whitespace in general (newline, space, tab etc), not just the space character.

        – bsa
        Sep 2 '13 at 6:14





        I'm not sure what you think "white spaces" are, but trim will remove whitespace in general (newline, space, tab etc), not just the space character.

        – bsa
        Sep 2 '13 at 6:14




        2




        2





        @bsa I came to understand he means "white space" in the visual sense, as in "visually blank areas in the results of rendering the HTML", and then he added in a comment above "except newlines caused by br tags".

        – Chris Baker
        Sep 3 '13 at 15:45







        @bsa I came to understand he means "white space" in the visual sense, as in "visually blank areas in the results of rendering the HTML", and then he added in a comment above "except newlines caused by br tags".

        – Chris Baker
        Sep 3 '13 at 15:45






        2




        2





        why is there not a check mark on an answer with 170 upvotes? SO confuses me sometimes.

        – tcoulson
        Feb 20 '18 at 20:39





        why is there not a check mark on an answer with 170 upvotes? SO confuses me sometimes.

        – tcoulson
        Feb 20 '18 at 20:39













        58














        var str = "  my awesome string   "
        str.trim();


        for old browsers, use regex



        str = str.replace(/^[ ]+|[ ]+$/g,'')
        //str = "my awesome string"





        share|improve this answer





















        • 2





          "[ ]" is exactly the same as " ". A character grouping of exactly one character is.. well... exactly one character.

          – Flimzy
          Mar 14 '15 at 23:40








        • 1





          @Flimzy: Yes, it would make more sense to write [tn ] or just s instead of [ ] which makes no sense.

          – erik
          Aug 11 '15 at 14:31
















        58














        var str = "  my awesome string   "
        str.trim();


        for old browsers, use regex



        str = str.replace(/^[ ]+|[ ]+$/g,'')
        //str = "my awesome string"





        share|improve this answer





















        • 2





          "[ ]" is exactly the same as " ". A character grouping of exactly one character is.. well... exactly one character.

          – Flimzy
          Mar 14 '15 at 23:40








        • 1





          @Flimzy: Yes, it would make more sense to write [tn ] or just s instead of [ ] which makes no sense.

          – erik
          Aug 11 '15 at 14:31














        58












        58








        58







        var str = "  my awesome string   "
        str.trim();


        for old browsers, use regex



        str = str.replace(/^[ ]+|[ ]+$/g,'')
        //str = "my awesome string"





        share|improve this answer















        var str = "  my awesome string   "
        str.trim();


        for old browsers, use regex



        str = str.replace(/^[ ]+|[ ]+$/g,'')
        //str = "my awesome string"






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 2 '13 at 23:54

























        answered Apr 2 '13 at 23:25









        KhanSharpKhanSharp

        7,89343747




        7,89343747








        • 2





          "[ ]" is exactly the same as " ". A character grouping of exactly one character is.. well... exactly one character.

          – Flimzy
          Mar 14 '15 at 23:40








        • 1





          @Flimzy: Yes, it would make more sense to write [tn ] or just s instead of [ ] which makes no sense.

          – erik
          Aug 11 '15 at 14:31














        • 2





          "[ ]" is exactly the same as " ". A character grouping of exactly one character is.. well... exactly one character.

          – Flimzy
          Mar 14 '15 at 23:40








        • 1





          @Flimzy: Yes, it would make more sense to write [tn ] or just s instead of [ ] which makes no sense.

          – erik
          Aug 11 '15 at 14:31








        2




        2





        "[ ]" is exactly the same as " ". A character grouping of exactly one character is.. well... exactly one character.

        – Flimzy
        Mar 14 '15 at 23:40







        "[ ]" is exactly the same as " ". A character grouping of exactly one character is.. well... exactly one character.

        – Flimzy
        Mar 14 '15 at 23:40






        1




        1





        @Flimzy: Yes, it would make more sense to write [tn ] or just s instead of [ ] which makes no sense.

        – erik
        Aug 11 '15 at 14:31





        @Flimzy: Yes, it would make more sense to write [tn ] or just s instead of [ ] which makes no sense.

        – erik
        Aug 11 '15 at 14:31











        11














        string.replace(/^s+|s+$/g, "");





        share|improve this answer
























        • Read the question, &nbsp; is used instead of an ordinary whitespace. On top of this, the whitespace is contained within a tag.

          – Rob W
          Apr 5 '12 at 16:07






        • 1





          It doesn't do what I need.

          – Sunil
          Apr 5 '12 at 16:16
















        11














        string.replace(/^s+|s+$/g, "");





        share|improve this answer
























        • Read the question, &nbsp; is used instead of an ordinary whitespace. On top of this, the whitespace is contained within a tag.

          – Rob W
          Apr 5 '12 at 16:07






        • 1





          It doesn't do what I need.

          – Sunil
          Apr 5 '12 at 16:16














        11












        11








        11







        string.replace(/^s+|s+$/g, "");





        share|improve this answer













        string.replace(/^s+|s+$/g, "");






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Apr 5 '12 at 16:06









        Sandeep ManneSandeep Manne

        4,77852850




        4,77852850













        • Read the question, &nbsp; is used instead of an ordinary whitespace. On top of this, the whitespace is contained within a tag.

          – Rob W
          Apr 5 '12 at 16:07






        • 1





          It doesn't do what I need.

          – Sunil
          Apr 5 '12 at 16:16



















        • Read the question, &nbsp; is used instead of an ordinary whitespace. On top of this, the whitespace is contained within a tag.

          – Rob W
          Apr 5 '12 at 16:07






        • 1





          It doesn't do what I need.

          – Sunil
          Apr 5 '12 at 16:16

















        Read the question, &nbsp; is used instead of an ordinary whitespace. On top of this, the whitespace is contained within a tag.

        – Rob W
        Apr 5 '12 at 16:07





        Read the question, &nbsp; is used instead of an ordinary whitespace. On top of this, the whitespace is contained within a tag.

        – Rob W
        Apr 5 '12 at 16:07




        1




        1





        It doesn't do what I need.

        – Sunil
        Apr 5 '12 at 16:16





        It doesn't do what I need.

        – Sunil
        Apr 5 '12 at 16:16











        6














        If you're working with a multiline string, like a code file:



        <html>
        <title>test</title>
        <body>
        <h1>test</h1>
        </body>
        </html>


        And want to replace all leading lines, to get this result:



        <html>
        <title>test</title>
        <body>
        <h1>test</h1>
        </body>
        </html>


        You must add the multiline flag to your regex, ^ and $ match line by line:



        string.replace(/^s+|s+$/gm, '');


        Relevant quote from docs:




        The "m" flag indicates that a multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string.







        share|improve this answer




























          6














          If you're working with a multiline string, like a code file:



          <html>
          <title>test</title>
          <body>
          <h1>test</h1>
          </body>
          </html>


          And want to replace all leading lines, to get this result:



          <html>
          <title>test</title>
          <body>
          <h1>test</h1>
          </body>
          </html>


          You must add the multiline flag to your regex, ^ and $ match line by line:



          string.replace(/^s+|s+$/gm, '');


          Relevant quote from docs:




          The "m" flag indicates that a multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string.







          share|improve this answer


























            6












            6








            6







            If you're working with a multiline string, like a code file:



            <html>
            <title>test</title>
            <body>
            <h1>test</h1>
            </body>
            </html>


            And want to replace all leading lines, to get this result:



            <html>
            <title>test</title>
            <body>
            <h1>test</h1>
            </body>
            </html>


            You must add the multiline flag to your regex, ^ and $ match line by line:



            string.replace(/^s+|s+$/gm, '');


            Relevant quote from docs:




            The "m" flag indicates that a multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string.







            share|improve this answer













            If you're working with a multiline string, like a code file:



            <html>
            <title>test</title>
            <body>
            <h1>test</h1>
            </body>
            </html>


            And want to replace all leading lines, to get this result:



            <html>
            <title>test</title>
            <body>
            <h1>test</h1>
            </body>
            </html>


            You must add the multiline flag to your regex, ^ and $ match line by line:



            string.replace(/^s+|s+$/gm, '');


            Relevant quote from docs:




            The "m" flag indicates that a multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string.








            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 28 '17 at 7:22









            Jaime GómezJaime Gómez

            5,73433232




            5,73433232























                4














                I know this is a very old question but it still doesn't have an accepted answer. I see that you want the following removed: html tags that are "empty" and white spaces based on an html string.



                I have come up with a solution based on your comment for the output you are looking for:



                Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces 





                var str = "<p>&nbsp;&nbsp;</p><div>&nbsp;</div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p>&nbsp;&nbsp;</p><div>&nbsp;</div>";
                console.log(str.trim().replace(/&nbsp;/g, '').replace(/<[^/>][^>]*></[^>]+>/g, ""));





                .trim() removes leading and trailing whitespace



                .replace(/&nbsp;/g, '') removes &nbsp;



                .replace(/<[^/>][^>]*></[^>]+>/g, "")); removes empty tags






                share|improve this answer




























                  4














                  I know this is a very old question but it still doesn't have an accepted answer. I see that you want the following removed: html tags that are "empty" and white spaces based on an html string.



                  I have come up with a solution based on your comment for the output you are looking for:



                  Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces 





                  var str = "<p>&nbsp;&nbsp;</p><div>&nbsp;</div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p>&nbsp;&nbsp;</p><div>&nbsp;</div>";
                  console.log(str.trim().replace(/&nbsp;/g, '').replace(/<[^/>][^>]*></[^>]+>/g, ""));





                  .trim() removes leading and trailing whitespace



                  .replace(/&nbsp;/g, '') removes &nbsp;



                  .replace(/<[^/>][^>]*></[^>]+>/g, "")); removes empty tags






                  share|improve this answer


























                    4












                    4








                    4







                    I know this is a very old question but it still doesn't have an accepted answer. I see that you want the following removed: html tags that are "empty" and white spaces based on an html string.



                    I have come up with a solution based on your comment for the output you are looking for:



                    Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces 





                    var str = "<p>&nbsp;&nbsp;</p><div>&nbsp;</div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p>&nbsp;&nbsp;</p><div>&nbsp;</div>";
                    console.log(str.trim().replace(/&nbsp;/g, '').replace(/<[^/>][^>]*></[^>]+>/g, ""));





                    .trim() removes leading and trailing whitespace



                    .replace(/&nbsp;/g, '') removes &nbsp;



                    .replace(/<[^/>][^>]*></[^>]+>/g, "")); removes empty tags






                    share|improve this answer













                    I know this is a very old question but it still doesn't have an accepted answer. I see that you want the following removed: html tags that are "empty" and white spaces based on an html string.



                    I have come up with a solution based on your comment for the output you are looking for:



                    Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces 





                    var str = "<p>&nbsp;&nbsp;</p><div>&nbsp;</div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p>&nbsp;&nbsp;</p><div>&nbsp;</div>";
                    console.log(str.trim().replace(/&nbsp;/g, '').replace(/<[^/>][^>]*></[^>]+>/g, ""));





                    .trim() removes leading and trailing whitespace



                    .replace(/&nbsp;/g, '') removes &nbsp;



                    .replace(/<[^/>][^>]*></[^>]+>/g, "")); removes empty tags






                    var str = "<p>&nbsp;&nbsp;</p><div>&nbsp;</div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p>&nbsp;&nbsp;</p><div>&nbsp;</div>";
                    console.log(str.trim().replace(/&nbsp;/g, '').replace(/<[^/>][^>]*></[^>]+>/g, ""));





                    var str = "<p>&nbsp;&nbsp;</p><div>&nbsp;</div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p>&nbsp;&nbsp;</p><div>&nbsp;</div>";
                    console.log(str.trim().replace(/&nbsp;/g, '').replace(/<[^/>][^>]*></[^>]+>/g, ""));






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Feb 22 '18 at 20:04









                    AnthonyAnthony

                    1,00311029




                    1,00311029























                        3














                        var trim = your_string.replace(/^s+|s+$/g, '');





                        share|improve this answer



















                        • 1





                          Will it remove white spaces like <br /> or <p>&nbsp;&nbsp;</p> <div>&nbsp;</div> ? Trmming simple spaces is not a problem. Its the white space removal that I am after.

                          – Sunil
                          Apr 4 '13 at 0:17











                        • will it remove white space

                          – user2086641
                          Aug 26 '13 at 5:53
















                        3














                        var trim = your_string.replace(/^s+|s+$/g, '');





                        share|improve this answer



















                        • 1





                          Will it remove white spaces like <br /> or <p>&nbsp;&nbsp;</p> <div>&nbsp;</div> ? Trmming simple spaces is not a problem. Its the white space removal that I am after.

                          – Sunil
                          Apr 4 '13 at 0:17











                        • will it remove white space

                          – user2086641
                          Aug 26 '13 at 5:53














                        3












                        3








                        3







                        var trim = your_string.replace(/^s+|s+$/g, '');





                        share|improve this answer













                        var trim = your_string.replace(/^s+|s+$/g, '');






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Apr 5 '12 at 16:07









                        SenorAmorSenorAmor

                        2,9511124




                        2,9511124








                        • 1





                          Will it remove white spaces like <br /> or <p>&nbsp;&nbsp;</p> <div>&nbsp;</div> ? Trmming simple spaces is not a problem. Its the white space removal that I am after.

                          – Sunil
                          Apr 4 '13 at 0:17











                        • will it remove white space

                          – user2086641
                          Aug 26 '13 at 5:53














                        • 1





                          Will it remove white spaces like <br /> or <p>&nbsp;&nbsp;</p> <div>&nbsp;</div> ? Trmming simple spaces is not a problem. Its the white space removal that I am after.

                          – Sunil
                          Apr 4 '13 at 0:17











                        • will it remove white space

                          – user2086641
                          Aug 26 '13 at 5:53








                        1




                        1





                        Will it remove white spaces like <br /> or <p>&nbsp;&nbsp;</p> <div>&nbsp;</div> ? Trmming simple spaces is not a problem. Its the white space removal that I am after.

                        – Sunil
                        Apr 4 '13 at 0:17





                        Will it remove white spaces like <br /> or <p>&nbsp;&nbsp;</p> <div>&nbsp;</div> ? Trmming simple spaces is not a problem. Its the white space removal that I am after.

                        – Sunil
                        Apr 4 '13 at 0:17













                        will it remove white space

                        – user2086641
                        Aug 26 '13 at 5:53





                        will it remove white space

                        – user2086641
                        Aug 26 '13 at 5:53











                        2














                        01). If you need to remove only leading and trailing white space use this:



                        var address = "  No.255 Colombo  "
                        address.replace(/^[ ]+|[ ]+$/g,'');


                        this will return string "No.255 Colombo"



                        02). If you need to remove all the white space use this:



                        var address = "  No.255 Colombo  "
                        address.replace(/s/g,"");


                        this will return string "No.255Colombo"






                        share|improve this answer




























                          2














                          01). If you need to remove only leading and trailing white space use this:



                          var address = "  No.255 Colombo  "
                          address.replace(/^[ ]+|[ ]+$/g,'');


                          this will return string "No.255 Colombo"



                          02). If you need to remove all the white space use this:



                          var address = "  No.255 Colombo  "
                          address.replace(/s/g,"");


                          this will return string "No.255Colombo"






                          share|improve this answer


























                            2












                            2








                            2







                            01). If you need to remove only leading and trailing white space use this:



                            var address = "  No.255 Colombo  "
                            address.replace(/^[ ]+|[ ]+$/g,'');


                            this will return string "No.255 Colombo"



                            02). If you need to remove all the white space use this:



                            var address = "  No.255 Colombo  "
                            address.replace(/s/g,"");


                            this will return string "No.255Colombo"






                            share|improve this answer













                            01). If you need to remove only leading and trailing white space use this:



                            var address = "  No.255 Colombo  "
                            address.replace(/^[ ]+|[ ]+$/g,'');


                            this will return string "No.255 Colombo"



                            02). If you need to remove all the white space use this:



                            var address = "  No.255 Colombo  "
                            address.replace(/s/g,"");


                            this will return string "No.255Colombo"







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 16 at 8:11









                            Chamila MaddumageChamila Maddumage

                            6401821




                            6401821






























                                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%2f10032024%2fhow-to-remove-leading-and-trailing-white-spaces-from-a-given-html-string%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

                                Create new schema in PostgreSQL using DBeaver

                                Deepest pit of an array with Javascript: test on Codility

                                Costa Masnaga