Remove \n using regular expression in javascript
I have a javascript string contains html table like this:
<div class="nobrtable"><table class="at"><TBODY><TR><td> FY
</TD><td> Profit Margin
</TD><td> Asset Turnover
</TD><td> RoA
</TD><td> Leverage Ratio
</TD><td> RoE
</TD><td> Cash Conversion
</TD><td> Cash RoE
</TD><td> RoC
</TD></TR><TR><td> 2002
</TD><td> 5.1%
</TD><td> 1.42
</TD><td> 7.2%
</TD><td> 127%
</TD><td> 9.2%
</TD><td> 163%
</TD><td> 14.9%
</TD><td> 16.9%
</TD></TR>
</TD></TR></TBODY></table></div>
How开发者_如何学运维 could I using regular expression to remove all the '\n' in the table? Otherwise it is too long.
I tried using
ele = ele.replace(/\n/g, ' ');
It will replace all the '\n' in my string. I just want to remove all the '\n' in all the html tables.
Thanks!
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
Try this:
ele = ele.replace(/\n<\/TD>/g, '</TD>');
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();
}
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.
精彩评论