Skip to content Skip to sidebar Skip to footer

Remove \n Using Regular Expression In Javascript

I have a javascript string contains html table like this:
FY Profi

Solution 1:

Try this:

ele = ele.replace(/\s+<\/TD>/g,' </TD>')

/m on the regex means match multi-line which helps matching on multiple \n's in a string.

UPDATE

  • dropped the /m modifier
  • changed \s* to \s+
  • introduced a whitespace character in the replacement string as browsers will render a whitespace character after your text in the TD, which you may want (though better to use no space and use CSS for padding/margins

Solution 2:

Try this:

ele = ele.replace(/\n<\/TD>/g, '</TD>');

Solution 3:

I'm not sure if you're talking about the HTML source or the inner HTML at runtime, butyou could try trimming the inner HTML of each TD element as follows:

var tds=document.getElementsByTagName('td'), i;
for (i=0; i<tds.length; i++) {
  tds[i].innerHTML = tds[i].innerHTML.trim();
}

Solution 4:

Assuming you have original text in a variable called html following should work for you:

var m = html.match(/<table[\s\S]*<\/table>/i);
var tableWithoutNewLine = m[0].replace(/\n/g, '');
html = html.replace(/<table[\s\S]*<\/table>/i, tableWithoutNewLine);

After this code variable html will have all the new line \n replaced between <table and </table tags only while leaving all other new lines and spaces intact.

Post a Comment for "Remove \n Using Regular Expression In Javascript"