Replace all text to a specific point

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

How can I do this in the opposite direction, replacing Meverything before him?

+3
source share
2 answers

Use expression /^.+M/:

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

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


A faster option is to use indexOfand substring:

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

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

+18
source

Here is another way to use the split method :

$(function(){
    var alphabet = "ABCDEFGHIJKLMNOPQRSTUVEXYZ";
    var replaced = alphabet.split("M")[1];
    $('body').text(replaced);
});
+1
source

All Articles