How to remove leading and trailing rendered as white spaces from a given HTML string? [closed] Ask Question

How to remove leading and trailing rendered as white spaces from a given HTML string? [closed] Ask Question

I've the following string containing HMTL. 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>

ベストアンサー1

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.

おすすめ記事