Matthew
Matthew

Reputation: 2246

Stop/Start JavaScript Increment at Certain Point

I have two sets of <ol> (ordered list), and I need the numbers to stop incrementing at the last <li> in each of the <ol>. My goal is to make the incrementing start over when it reaches the last <li>.

For example, if you go the the Fiddle, and click "list", it returns:

1. Hello world! :)
2. Hello how are you
3. good

- Hello world! :)
- Hello how are you
- good

4. Hello world! :)
5. Hello how are you
6. good

I want the incrementing to NOT affect all <li> inside of the <ol>. I want the incrementing to stop at the last <li>. In this case, 3. good

In other words, this is what I want to be returned:

1. Hello world! :)
2. Hello how are you
3. good

- Hello world! :)
- Hello how are you
- good

1. Hello world! :)
2. Hello how are you
3. good

Here is my function(){...}

function doIt() {
var input = document.getElementById("h");
var olPatt = /<ol>\s*((?:<li>.+<\/li>\s*)+)<\/ol>/g; // recognizes ordered list
var ulPatt = /<ul>\s*((?:<li>.+<\/li>\s*)+)<\/ul>/g; // recognizes unordered list
var ol = input.value.match(olPatt); // returns olPatt match from value
// var olPattAfter = ol.match(/(?:[0-9]+\.\s.+)/g); // this is supposed to return 1.,2.,3.,4.,5.,6, from ol
// var ol = result.value.match(olPatt);
// var olLi = ol.match(/<li>/g);
var ulPatt = /<ul>\s*((?:<li>.+<\/li>\s*)+)<\/ul>/g;
var i = 1;

input.value = input.value.replace(olPatt, function (n, listItems) {
    return listItems.replace(/\s*<li>/g, function () {
    return i++ + '.' + ' ';
    }).replace(/<\/li>/g, '\n');
});

input.value = input.value.replace(ulPatt, function (n, listItems) {
    return listItems.replace(/\s*<li>/g, function() {return '-' + ' ';}).replace(/<\/li>/g, '\n');
});
}

Upvotes: 1

Views: 759

Answers (1)

Fabricator
Fabricator

Reputation: 12782

Restart the counter in the replace callback:

var ulPatt = /<ul>\s*((?:<li>.+<\/li>\s*)+)<\/ul>/g;

input.value = input.value.replace(olPatt, function (n, listItems) {
    var i = 1;
    return listItems.replace(/\s*<li>/g, function () {
    return i++ + '.' + ' ';
    }).replace(/<\/li>/g, '\n');
});

fiddle

Upvotes: 2

Related Questions