How would I replace this:
<p class='abc'>blah blah</p> afdads
With this:
blah blah <br/>
Using (vanilla?) JavaScript?
Thanks!
Updated Content
$content = $_REQUEST['content'];
$content = preg_replace('/<p[^>]*>/', '', $content); // Remove the start <p> or <p attr="">
$content = preg_replace('/</p>/', '<br />', $content); // Replace the end
echo $content; // Output content without P tags
I would something like this...hope this time you mates have got my question.
Thankyou
How would I replace this:
<p class='abc'>blah blah</p> afdads
With this:
blah blah <br/>
Using (vanilla?) JavaScript?
Thanks!
Updated Content
$content = $_REQUEST['content'];
$content = preg_replace('/<p[^>]*>/', '', $content); // Remove the start <p> or <p attr="">
$content = preg_replace('/</p>/', '<br />', $content); // Replace the end
echo $content; // Output content without P tags
I would something like this...hope this time you mates have got my question.
Thankyou
Share Improve this question edited Jun 16, 2011 at 14:46 GitsD asked Jun 16, 2011 at 14:33 GitsDGitsD 6682 gold badges8 silver badges16 bronze badges 4- Would you accept jQuery as a solution? – Blender Commented Jun 16, 2011 at 14:35
- i have updated my question..please help guys – GitsD Commented Jun 16, 2011 at 14:47
- That’s not JavaScript, it’s PHP. – Daniel Cassidy Commented Jun 16, 2011 at 15:04
- I know thats php but i want that in javacritp daniel... – GitsD Commented Jun 16, 2011 at 15:18
4 Answers
Reset to default 13Thank you for posting this question, you're a lifesaver, GitsD.
I replaced your php function to javascript and it worked!
content = content.replace(/<p[^>]*>/g, '').replace(/<\/p>/g, '<br />');
content would now replaced p tags with '' and /p tags with br
You could do (if you talk about strings)
var str = "<p class='abc'>blah blah</p> afdads";
str = str.replace("<p class='abc'>", "");
str = str.replace("</p> afdads", " <br/>");
//str = "blah blah <br/>"
I'm afraid your question isn't well-specified. Assuming you want to do that to all p tags with that class, and you're working in a web browser environment:
var paras = document.getElementsByTagName('p')
for (var i = 0; i < paras.length; ) {
if (paras[i].className.match(/\babc\b/)) {
var h = paras[i].innerHTML
, b = document.createElement('br')
, t = document.createTextNode(h)
, p = paras[i].parentNode
p.replaceChild(b, paras[i])
p.insertBefore(t, b)
}
else {
i++
}
}
If you actually meant JavaScript and not PHP, this would do it:
var ps = document.getElementsByTagName('p');
while (ps.length) {
var p = ps[0];
while (p.firstChild) {
p.parentNode.insertBefore(p.firstChild, p);
}
p.parentNode.insertBefore(document.createElement('br'), p);
p.parentNode.removeChild(p);
}
This works because the NodeList
returned by getElementsByTagName
is ‘live’, meaning that when we remove a p
node from the document, it also gets removed from the list.