How to remove leading and trailing white spaces from a given html string?
Solution 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.
Solution 2
var str = " my awesome string "
str.trim();
for old browsers, use regex
str = str.replace(/^[ ]+|[ ]+$/g,'')
//str = "my awesome string"
Solution 3
string.replace(/^\s+|\s+$/g, "");
Solution 4
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>";
console.log(str.trim().replace(/ /g, '').replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
.trim()
removes leading and trailing whitespace
.replace(/ /g, '')
removes
.replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
removes empty tags
Solution 5
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.
Related videos on Youtube
![Sunil](https://i.stack.imgur.com/Y5RQs.jpg?s=256&g=1)
Sunil
I have extensive experience working with .Net and ASP.Net in various projects for the last 18 years and also, I am a Microsoft Certified Solutions Developer in web applications (MCSD). My passion is development at all levels including ui, database and web services/web api. Currently, I am actively looking for development work in the .Net area.
Updated on January 10, 2020Comments
-
Sunil over 4 years
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>
-
musefan about 12 years
-
Rob W about 12 yearsWhat is your real problem? Do you want to remove whitespace before inserting nodes in the document?
-
Sunil about 12 yearsI 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 about 12 yearsSo in my example, I finally should get the following after trimming: Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces
-
Chris Baker almost 10 years@Sunil I don't know if you ever solved this, but you could try one of these solutions: stackoverflow.com/questions/16708158/…
-
Yash about 8 yearsRemoving and Replacing Spaces with some Character by using 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 samplesLeft:{/^[\s]+/g} Right:{/\s+$/g}
Trim
:{/^\s+|\s+$/g}`
-
-
Rob W about 12 yearsRead the question,
is used instead of an ordinary whitespace. On top of this, the whitespace is contained within a tag. -
PeeHaa about 12 yearsI would prefer a regex way, becaase it isn't supported in all browsers (cough cough IE < 9).
-
Sunil about 12 yearsTrim method will not trim white spaces, but only spaces. So its not what I am looking for.
-
Sunil about 11 yearsWill it remove white spaces like <br /> or <p> </p> <div> </div> ? Trmming simple spaces is not a problem. Its the white space removal that I am after.
-
user2086641 almost 11 yearswill it remove white space
-
bsa almost 11 yearsI'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.
-
Chris Baker almost 11 years@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". -
Flimzy over 9 years"[ ]" is exactly the same as " ". A character grouping of exactly one character is.. well... exactly one character.
-
erik almost 9 years@Flimzy: Yes, it would make more sense to write
[\t\n\ ]
or just\s
instead of[ ]
which makes no sense. -
tcoulson over 6 yearswhy is there not a check mark on an answer with 170 upvotes? SO confuses me sometimes.
-
babgyy almost 6 years@tcoulson to get the check mark, the poster has to accept the answer. It does'nt matter how many upvotes it gets.
-
tcoulson almost 6 years@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.
-
babgyy over 5 years@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
-
tcoulson over 5 yearsWhat 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 over 5 yearseven 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.
-
Chris Baker over 5 yearsI 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.