TravelWhere TravelWhere - 3 months ago 8
Javascript Question

Add increment number at the end for every line

Currently I wrote a script to add a prefix & suffix to each line but now I don't know how to add an increment number at the end of the prefix. This is the code so far:



var prefix = '<a href=\"<phpcode><?php echo get_permalink( $post->ID ); ?></phpcode>';
var suffix = '</a><!--nextpage-->';
var txt = "http://www.domain.com/\nhttp://www.domain.com/\nhttp://www.domain.com/";
var final = prefix + txt.split('\n').join(suffix + '\n' + prefix) + suffix;
alert(final);





I want my final output to look like this:

<a href="<phpcode><?php echo get_permalink( $post->ID ); ?></phpcode>http://www.domain.com/2</a><!--nextpage-->
<a href="<phpcode><?php echo get_permalink( $post->ID ); ?></phpcode>http://www.domain.com/3</a><!--nextpage-->
<a href="<phpcode><?php echo get_permalink( $post->ID ); ?></phpcode>http://www.domain.com/4</a><!--nextpage-->


I want the number to increment starting from 2. I don't exactly know how I would add an increment number at the end of the prefix for each line

Answer

If you want to keep it more similar to your original, you can just use .map before your .join instead of looping

    var c = 2;
    var prefix = '<a href=\"<phpcode><?php echo get_permalink( $post->ID ); ?></phpcode>';
    var suffix = '</a><!--nextpage-->';
    var txt = "http://www.domain.com/\nhttp://www.domain.com/\nhttp://www.domain.com/";
    var final = txt.split('\n').map(function(txt){return prefix + txt + c++ + suffix + '\n'; }).join("");
    alert(final);