Regex Math

This would be useful if you need to switch from a zero-based index to another base

by Mottie

HTML

<h3>URL Search String Replacements:</h3>
<label>Index:</label> <input type="number" value="0"/><br/>

<label>Basic replacement</label><br> 
<input type="text" value="&index={index}" /> &rarr; <span></span><br>

<label>Regex math (switch from zero-based to one-based index)<br>
    (replace the "+1" with different numbers, negative &amp; positive)</label><br>
<input type="text" value="&index={index+1}" /> &rarr; <span></span>

CSS

input { margin-bottom: 20px; }
span { color: red; }

JavaScript

$('input').on('change', function(){

    var index = parseInt( $('input:first').val(), 10 ),
    search1 = $('input:eq(1)').val(),
    search2 = $('input:last').val(),
    
    // basic replacement
    result1 = search1.replace(/\{index\}/, index),
    
    // regex math
    result2 = search2
        .replace(/\{index([-+]\d+)?\}/g, function(fullstring, match){
            return index + (match ? parseInt(match, 10) : 0);
        });

    $('span:first').html(result1);
    $('span:last').html(result2);

}).change();