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>
RBT
  • 24,161
  • 21
  • 159
  • 240
Sunil
  • 20,653
  • 28
  • 112
  • 197
  • [check this](http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript) – musefan Apr 05 '12 at 16:06
  • What is your real problem? Do you want to remove whitespace before inserting nodes in the document? – Rob W Apr 05 '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 05 '12 at 16:17
  • So in my example, I finally should get the following after trimming: Trimming using JavaScript



    all leading and trailing white spaces
    – Sunil Apr 05 '12 at 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-javascript – Chris Baker Aug 01 '14 at 00:01
  • _Removing and Replacing Spaces with some Character by using_ [**RegExp**](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/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 Apr 27 '16 at 14:10

7 Answers7

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.

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
  • 4
    I would prefer a regex way, becaase it isn't supported in all browsers (*cough cough* IE < 9). – PeeHaa Apr 05 '12 at 16:07
  • 2
    Trim method will not trim white spaces, but only spaces. So its not what I am looking for. – Sunil Apr 05 '12 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 02 '13 at 06: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 03 '13 at 15:45
  • 3
    why is there not a check mark on an answer with 170 upvotes? SO confuses me sometimes. – tcoulson Feb 20 '18 at 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 Oct 01 '18 at 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 Oct 01 '18 at 14:07
  • 1
    @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 question – babgyy Oct 02 '18 at 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 Oct 02 '18 at 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 Oct 02 '18 at 15:17
  • 2
    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 ` `'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 Oct 02 '18 at 20:38
73
var str = "  my awesome string   "
str.trim();    

for old browsers, use regex

str = str.replace(/^[ ]+|[ ]+$/g,'')
//str = "my awesome string" 
Jhankar Mahbub
  • 9,746
  • 10
  • 49
  • 52
  • 2
    "[ ]" is exactly the same as " ". A character grouping of exactly one character is.. well... exactly one character. – Jonathan Hall Mar 14 '15 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 '15 at 14:31
13
string.replace(/^\s+|\s+$/g, "");
Sandeep Manne
  • 6,030
  • 5
  • 39
  • 55
  • Read the question, ` ` is used instead of an ordinary whitespace. On top of this, the whitespace is contained within a tag. – Rob W Apr 05 '12 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.

Jaime Gómez
  • 6,961
  • 3
  • 40
  • 41
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

Anthony
  • 1,439
  • 1
  • 19
  • 36
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"

Chamila Maddumage
  • 3,304
  • 2
  • 32
  • 43
3
var trim = your_string.replace(/^\s+|\s+$/g, '');
SenorAmor
  • 3,351
  • 16
  • 27