2

How can this code be written in a simplified manner?

text.replace('</p>','<br/>').replace('</P>','<br/>');
7
  • 1
    What happens to the opening <p>-tag? And: Your code replaces the first occurrence only. I do not think that this is what you need. And: HTML manipulation using its string representation? In JavaScript? Seriously? And: Its <br />, not <br/>! Commented Jan 20, 2011 at 14:55
  • this part of the code, <p> tag should be not replace Commented Jan 20, 2011 at 14:59
  • @Yosef: Wouldn't that result in invalid markup? Omitting a closing tag is usually a bad idea. Commented Jan 20, 2011 at 15:00
  • @Yosef - then you are creating malformed HTML, which the browser will correct anyway when building the DOM. Commented Jan 20, 2011 at 15:00
  • @elusive @Kobi I think he is keeping the last closing tag by some condition =). So you get a lot of breaks and then the last closing tag again. Seems fine to me. Commented Jan 20, 2011 at 15:03

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@Yosef - Already there, even used a jQuery example. However, you need to explain better what you're trying to do :)
$('p').replaceWith('<br />'); would replace the complete p and content with a breakline, right?
@Marnix - Correct! As I've said, it isn't too clear what the OP is aiming for here, this is just an example.

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.