UserIsCorrupt UserIsCorrupt - 1 month ago 10
jQuery Question

Replace all text before a certain point

$(function(){
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVEXYZ";
var replaced = alphabet.replace(/(M).+$/,'');
$('body').text(replaced);
});


How can I make this go in the opposite direction, replacing
M
and everything before it?

Answer

Use /^.+M/ expression:

$(function() {
    var alphabet = "ABCDEFGHIJKLMNOPQRSTUVEXYZ";
    var replaced = alphabet.replace(/^.+M/,'');
    $('body').text(replaced);
});

DEMO: http://jsfiddle.net/kbZhU/1/


The faster option is to use indexOf and substring methods:

$(function(){
    var alphabet = "ABCDEFGHIJKLMNOPQRSTUVEXYZ";
    var replaced = alphabet.substring(alphabet.indexOf("M") + 1);
    $('body').text(replaced);
});

DEMO: http://jsfiddle.net/kbZhU/2/‚Äč