4

I have some HTML content inside a JavaScript variable:

var string="<tr>  <td> data 1 </td> <td> data 2 </td>   <td> data 3 </td></tr>";

I want to remove the white spaces between HTML tags only. The White space in column data must be remain same.

string.replace(/\n/g, "");
string.replace(/[\t ]+\</g, "<");
string.replace(/\>[\t ]+\</g, "><");
string.replace(/\>[\t ]+$/g, ">");

I tried the above code. But this is not worked. Some one please help me to solve this problem.

3
  • Are you trying to remove the first and last space of your var string=" data 1 data 2 data 3 " so that it becomes var string="data 1 data 2 data 3" Commented Jan 8, 2015 at 13:22
  • Exactly what spaces do you want to remove? All spaces in the string in your example are between tags (at least between the first tag <tr> and the last tag </tr>). And why? You have probably made a wrong analysis of some problem. Commented Jan 8, 2015 at 14:49
  • 1
    Possible duplicate of Remove every white space between tags using JavaScript Commented Feb 5, 2019 at 19:04

3 Answers 3

22
string= string.replace(/>\s+</g,'><');
Sign up to request clarification or add additional context in comments.

Comments

5

There is a jQuery solution:

Use .contents() and .filter() to find all whitespace-only text nodes and remove() them, like this:

var $e = $("<tr>  <td> data 1 </td> <td> data 2 </td>   <td> data 3 </td></tr>");
$e.contents().filter(function() {
  return this.nodeType = Node.TEXT_NODE && /\S/.test(this.nodeValue) === false;
}).remove();
console.log($e.html());
// <td> data 1 </td><td> data 2 </td><td> data 3 </td>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Check console!

The above example filters children of tr. However, it is also possible to check descendants or make complex decisions such as keep whitespace between inline elements but remove between block elements.

Comments

1

Ignoring < and > chars inside text nodes:

var string = "<p>lol</p>  <p>let's remove <span>spaces between tags</span> </p>";
var rexp = new RegExp(">[\t\s ]*<", "g");
var result = string.replace(rexp, "><");

js fiddle here: http://jsfiddle.net/4cfgnfrx/

with your example: http://jsfiddle.net/4cfgnfrx/1/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.