Last Updated: February 25, 2016
·
730
· bitkomponist

javascript string replace

to get a string replace functionality do as follows:

var myString = "javascript can be used in a browser"

myString = myString.split("in a browser").join("everywhere");

//new content of myString: javascript can be used everywhere

example usage in a reallife scenario

function replaceMarkers(str,markers){
    var marker;
    for(marker in markers){
        if(markers.hasOwnProperty(marker))
            str = str.split("{{"+marker+"}}").join(markers[marker]);
    }
    return str;
}

var myString = replaceMarkers(
    "Hi, my name is {{firstname}} {{lastname}}"
    ,{"firstname":"John", "lastname":"Doe"}
);
console.log(myString); // outputs: Hi, my name is John Doe

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside