开发者

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, and g 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜