0

I have a list written in HTML:

<p>
1 - hello
2 - yo
3 - sup
</p>

I want to replace the number [1-20] followed by the space[ ] followed by the hyphen[-] with &quot;<p class='answer'>&quot;using Jquery.


I believe it is something like this? (obviously inside the .find is just explaining what I am looking for):

$( "p" ).find( "#[1-20] -" ).replaceWith( "&quot;<p class='answer'>&quot;" );
2
  • 1
    maybe you could start using a real unsorted html list instead of a paragraph tag? <ul><li></li>...</ul> Commented Jan 1, 2014 at 12:01
  • 1
    Unclosed p element inside another p element? That's an invalid markup. Commented Jan 1, 2014 at 12:13

2 Answers 2

1

This is a clean(*) solution.

$("p:not(:has(*))").each(function () {
    var txt = $(this).text(),
        linePattern = /^\s*(\d+) - (.*)/gm,
        line, paragraphs = [];

    if (linePattern.test(txt)) {
        linePattern.lastIndex = 0;
        while (line = linePattern.exec(txt)) {
            paragraphs.push( $("<p>", {text: '"' + line[2] + '"'}) );
        }
        $(this).replaceWith(paragraphs);
    }
});

(*) "Clean" as in: DOM-aware and XSS-safe, straight-forward and maintainable.

It converts

<p>
1 - hello
2 - yo
3 - sup
</p>

to

<p>"hello"</p><p>"yo"</p><p>"sup"</p>
Sign up to request clarification or add additional context in comments.

Comments

0

try like this

var htmlstr = $('p').html(); 
  var splitstr = htmlstr.split('-') ;
  var toreplace = splitstr[0];
  var replacewith = "&quot;<p class='answer'>&quot;";
  splitstr.replace(toreplace,replacewith )

2 Comments

replace don't change source string unlike replaceWitn
what output do you want from the html you mentioned in your question

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.