0

I'm trying to replace the <li> with 1. 2. 3. respectively. I managed to change the <li> to a number, but that number is 0. The loop doesn't want to work. To be honest, this method may be impossible.

Take a look at the Fiddle if you'd like.

This is my function(){...} :

function doIt(){

        var input = document.getElementById("input");
        var li = /<li>/; // match opening li
        var liB = /<\/li>/; // match closing li
        var numberOfItems = input.value.match(li).length; // number of lis that occur


        for(var i = 0; i < numberOfItems; i++) {
            insertNumber(i); // execute insertNumber function w/ parameter of incremented i 
        }

        function insertNumber(number){
            input.value = input.value.replace(li, number + "." + " ").replace(liB, "");
        }


    }

I understand the insertNumber(){...} function is not necessary.

7
  • numberOfItems is undefined. Commented Jun 26, 2014 at 2:06
  • 1
    In your first loop you replace ALL <li>s (with 0)... in your 2nd there is nothing left to replace. Maybe remove the gi from your regex. Commented Jun 26, 2014 at 2:10
  • 1
    Like @christian314159 said, after the first iteration there are no more <li> in the text. Some debugging code would reveal it to you. And please put a full code example in the question instead of just linking. Commented Jun 26, 2014 at 2:12
  • 2
    Consider an approach like this. It's a bit simpler. Commented Jun 26, 2014 at 2:16
  • 2
    The .replace() method specifically allows a function as the second argument. Its return value becomes the replacement. Commented Jun 26, 2014 at 2:21

1 Answer 1

1

Here's an alternative method, turning your HTML textarea contents into DOM elements that jQuery can manipulate and managing them that way:

function doIt() {
    var $domElements = $.parseHTML( $('#input').val().trim() ),
        output = [],
        i = 1;
    $.each($domElements, function(index, element) {
        if($(this).text().trim() != '') {
            output.push( i + '. ' + $(this).text().trim() );
            i++;
        }
    });
    $('#input').val(output.join('\n'));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Incidentally you can also do output.push(i++ + '....') and remove the extra line, but this is amusingly difficult to read
That works, thanks! I really appreciate the help, and I will definitely look back at this later. I want to use a raw JavaScript approach, because I feel that I should have full comprehension of a language before diving into a library of it. I'm going to use @cookiemonster 's method.

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.