209

I've 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>
6
  • check this
    – musefan
    Apr 5, 2012 at 16:06
  • What is your real problem? Do you want to remove whitespace before inserting nodes in the document?
    – Rob W
    Apr 5, 2012 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, 2012 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, 2012 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/… Aug 1, 2014 at 0:01

7 Answers 7

284

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.

11
  • 4
    I would prefer a regex way, becaase it isn't supported in all browsers (cough cough IE < 9).
    – PeeHaa
    Apr 5, 2012 at 16:07
  • 2
    Trim method will not trim white spaces, but only spaces. So its not what I am looking for.
    – Sunil
    Apr 5, 2012 at 16:20
  • 11
    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, 2013 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". Sep 3, 2013 at 15:45
  • 3
    why is there not a check mark on an answer with 170 upvotes? SO confuses me sometimes.
    – tcoulson
    Feb 20, 2018 at 20:39
73
var str = "  my awesome string   "
str.trim();    

for old browsers, use regex

str = str.replace(/^[ ]+|[ ]+$/g,'')
//str = "my awesome string" 
2
  • 2
    "[ ]" is exactly the same as " ". A character grouping of exactly one character is.. well... exactly one character. Mar 14, 2015 at 23:40
  • 2
    @Flimzy: Yes, it would make more sense to write [\t\n\ ] or just \s instead of [ ] which makes no sense.
    – erik
    Aug 11, 2015 at 14:31
13
string.replace(/^\s+|\s+$/g, "");
1
  • 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, 2012 at 16:07
10

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.

10

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

6

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"

3
var trim = your_string.replace(/^\s+|\s+$/g, '');
2
  • 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, 2013 at 0:17
  • will it remove white space Aug 26, 2013 at 5:53

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.