var str1 = "I learn JavaScript";
var str2 = str1.replace( "JavaScript", "PHP" );
alert( str2 ); // 'I learn PHP'
Tip: for case-insensitive searches, use toLowerCase() or toUpperCase() on the "searched" string, which will only change letter casing in the returned copy, not the original string: var str2 = str1.toLowerCase().replace( "javascript", "PHP" );
var str = "John Smith is the CEO of Smith Widgets, Inc.";
var rgx = /smith/gi; // case-insensitive; replace all
alert( str.replace( rgx , "Johnson" ) );
Note: the "gi" modifiers after the RegEx literal tell JavaScript that the regular expression pattern should be global ("g" - capture all matches), and case-insensitive ("i").
str = str.replace(/TX/g,"Texas").replace(/NY/g,"New York"); // etc.
$str = 'I learn PHP';
echo preg_replace( '/php/i', 'JavaScript', $str ); // 'I learn JavaScript'
Sister method: search() looks for string literals or RegExp in a string and returns the matched character position index (more flexible than indexOf(), which doesn't accept regular expressions).