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

Go To StackoverFlow.com

154

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>
2012-04-05 16:04
by Sunil
check thismusefan 2012-04-05 16:06
What is your real problem? Do you want to remove whitespace before inserting nodes in the document - Rob W 2012-04-05 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 2012-04-05 16:17
So in my example, I finally should get the following after trimming: Trimming using JavaScript



all leading and trailing white space - Sunil 2012-04-05 16:23
@Sunil I don't know if you ever solved this, but you could try one of these solutions: http://stackoverflow.com/questions/16708158/remove-html-tags-except-br-or-br-tags-with-javascrip - Chris Baker 2014-08-01 00:01
Removing and Replacing Spaces with some Character by using RegExp. var str = ' \r \t \n Remove \n leading and \t trailing white spaces \r \t \n '; String.prototype.singleSpace = function( ) { return this.replace( new RegExp(/^[\s]+$/, 'gm'), '' ).replace( new RegExp('\\s+', 'gm'), ' ' ); } console.log('Single Space B/W Words :', str.singleSpace().toUpperCase() );

some RegExp samples Left:{/^[\s]+/g} Right:{/\s+$/g} Trim:{/^\s+|\s+$/g} - Yash 2016-04-27 14:10



224

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.

2012-04-05 16:06
by Chris Baker
I would prefer a regex way, becaase it isn't supported in all browsers (cough cough IE < 9) - PeeHaa 2012-04-05 16:07
Trim method will not trim white spaces, but only spaces. So its not what I am looking for - Sunil 2012-04-05 16:20
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 2013-09-02 06:14
@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 2013-09-03 15:45
why is there not a check mark on an answer with 170 upvotes? SO confuses me sometimes - tcoulson 2018-02-20 20:39
@tcoulson to get the check mark, the poster has to accept the answer. It does'nt matter how many upvotes it gets - babgyy 2018-10-01 13:38
@babgyy Duh, I know how the site works, it is just shocking to me that someone wouldn't accept an answer that is CLEARLY better than the others. I mean now 202 people found this to win - tcoulson 2018-10-01 14:07
@tcoulson Being the better answer doesn't mean it answers the question. Don't get me wrong, I upvoted it too, but it doesn't answer the questio - babgyy 2018-10-02 15:03
What are you talking about? It solved it for me. It's not even my answer I am fighting for. Just think it is weak when SO doesn't reward properly - tcoulson 2018-10-02 15:14
even if this didn't answer it fully, there are over 300 upvotes on various questions, it is irresponsible of the question poster to not choose an answer - tcoulson 2018-10-02 15:17
"It solved it for me" Good for you ! Apparently, it doesn't solve it for the OP. That's all there is to it, now let's stop arguing about something completely irrelevant to this SO question, I just wanted to help you understand, but apparently you have it all figured it out, even better than the creators of SO. Congrat - babgyy 2018-10-02 15:48
I fundamentally misunderstood his question due to semantics. The only answer that even attempts to address the removal of visual white space excluding br's is Anthony's. If the OP is only dealing with &nbsp;'s making the elements empty, there are a few approaches one could use, Anthony's is one. I don't support the use of regex on HTML so I wouldn't use Anthony's approach (I favor of DOM manipulation), but he's the only one who approached the OP's problem correctly understood. I left my answer up since it seems to be helpful, but it isn't the answer to the OP. I'm fine with how it works - Chris Baker 2018-10-02 20:38


57

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

for old browsers, use regex

str = str.replace(/^[ ]+|[ ]+$/g,'')
//str = "my awesome string" 
2013-04-02 23:25
by KhanSharp
"[ ]" is exactly the same as " ". A character grouping of exactly one character is.. well... exactly one character - Flimzy 2015-03-14 23:40
@Flimzy: Yes, it would make more sense to write [\t\n\ ] or just \s instead of [ ] which makes no sense - erik 2015-08-11 14:31


11

string.replace(/^\s+|\s+$/g, "");
2012-04-05 16:06
by Sandeep Manne
Read the question, &nbsp; is used instead of an ordinary whitespace. On top of this, the whitespace is contained within a tag - Rob W 2012-04-05 16:07
It doesn't do what I need - Sunil 2012-04-05 16:16


5

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.

2017-03-28 07:22
by Jaime Gómez


3

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

2018-02-22 20:04
by Anthony


2

var trim = your_string.replace(/^\s+|\s+$/g, '');
2012-04-05 16:07
by SenorAmor
Will it remove white spaces like
or

  

 
? Trmming simple spaces is not a problem. Its the white space removal that I am after - Sunil 2013-04-04 00:17
will it remove white spac - user2086641 2013-08-26 05:53


0

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"

2019-01-16 08:11
by Chamila Maddumage
Ads