javascript string remove code example

Example 1: javascript replace string

var str = "JavaScript replace method test";
var res = str.replace("test", "success");  
//res = Javscript replace method success

Example 2: javascript replace all occurrences of string

function replaceAll(str, find, replace) {
    var escapedFind=find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    return str.replace(new RegExp(escapedFind, 'g'), replace);
}
//usage example
var sentence="How many shots did Bill take last night? That Bill is so crazy!";
var blameSusan=replaceAll(sentence,"Bill","Susan");

Example 3: remove substring from string javascript

var ret = "data-123".replace('data-','');

Example 4: js remove string from string

var ret = "data-123".replace('data-','');
console.log(ret);   //prints: 123

Example 5: js remove string from string

var ret = "data-123".replace(/data-/g,'');

Example 6: how to remove part of string in javascript

var str = "test_23";
alert(str.split("_").pop());
// -> 23

var str2 = "adifferenttest_153";
alert(str2.split("_").pop());
// -> 153

Tags: