Simplifying text.replace() in Javascript
How can this code be written in a simplified ma开发者_Python百科nner?
text.replace('</p>','<br/>').replace('</P>','<br/>');
You can write:
text.replace(/<\/p>/ig,'<br/>');
/<\/p>/
is the regex, which matches the literal string./
is escaped because it is the regex delimiter in JavaScript./ig
are the regex flags -i
for case-insensitive, andg
for global, to replace more than the first</p>
.
However, JavaScript has much better tools for dealing with the DOM structure, you can do better than manipulating raw source code. For example, using jQuery you can write:
$('p').replaceWith('<br />');
or:
$('p').after('<br />');
None of them may do what you need, but it is probably easier and more robust without sting manipulations.
精彩评论