I've the following HTML string. What would be sample code in JavaScript to remove leading and trailing white spaces from this string?
<p> </p>
<div> </div>
Trimming using JavaScript<br />
<br />
<br />
<br />
all leading and trailing white spaces
<p> </p>
<div> </div>
This question is related to
javascript
removing-whitespace
var str = " my awesome string "
str.trim();
for old browsers, use regex
str = str.replace(/^[ ]+|[ ]+$/g,'')
//str = "my awesome string"
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"
var trim = your_string.replace(/^\s+|\s+$/g, '');
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.
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.
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> </p><div> </div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p> </p><div> </div>";_x000D_
console.log(str.trim().replace(/ /g, '').replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
_x000D_
.trim()
removes leading and trailing whitespace
.replace(/ /g, '')
removes
.replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
removes empty tags
string.replace(/^\s+|\s+$/g, "");
Source: Stackoverflow.com