203

I've the following string containing HTML. What would be sample code in JavaScript to remove leading and trailing white spaces that would appear in the rendering of this string? In other words: how can I obtain a string that would not show any leading or training white spaces in the HTML rendering, but otherwise be identical?

<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>
14
  • 2
    What is your real problem? Do you want to remove whitespace before inserting nodes in the document? Commented Apr 5, 2012 at 16:06
  • 6
    This question really need to be updated to be a lot more explicit about what "removing leading and trailing whitespaces" means in this context. providing the desired output would be a good start. (Some of this information is possibly in comments on the question and answers, but people shouldn't have to dig through those to understand the question.) Commented Mar 14, 2024 at 1:37
  • 7
    This question is being discussed on meta: meta.stackoverflow.com/q/429472 Commented Mar 14, 2024 at 3:30
  • 3
    What could possibly happen for so many people to misinterpret this question? Surely, the question is not very well written, but it's not terrible either and the author's intent is clear from the question alone, at least to me. This is a very good question and should have a clear answer. Commented Mar 14, 2024 at 9:20
  • 3
    Even after the edits, this is still unclear. For one thing, the question doesn't include desired output for the example document. For another, there are LOTS of potential ambiguities! Should empty tags like <p></p> get removed (if leading or trailing)? What about tags not meant to hold text, like an <img>? Should we only delete entire elements or should we e.g. trim <p>&nbsp;foo</p> to <p>foo</p>? What about literal newline and space characters between tags that with default CSS won't render but could with white-space: pre? What about <pre> elements? Probably there's more... Commented Mar 15, 2024 at 13:55

7 Answers 7

278

See the String method trim():

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

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

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 which are still swimming in the shallow end of the pool.

Sign up to request clarification or add additional context in comments.

5 Comments

I would prefer a regex way, becaase it isn't supported in all browsers (cough cough IE < 9).
Trim method will not trim white spaces, but only spaces. So its not what I am looking for.
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 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".
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.
67

Use:

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

For old browsers, use a regular expression:

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

2 Comments

"[ ]" is exactly the same as " ". A character grouping of exactly one character is.. well... exactly one character.
@Flimzy: Yes, it would make more sense to write [\t\n\ ] or just \s instead of [ ] which makes no sense.
18

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

1 Comment

It works on "that" example, but it's not a great piece of code because it erases &nbsp; entities which may not be the leading/trailing ones.
4
string.replace(/^\s+|\s+$/g, "");

1 Comment

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

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 documentation:

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.

Comments

-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".

Comments

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

2 Comments

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.
will it remove white space

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.