This is a simple one. I want to replace a sub-string with another sub-string on client-side using Javascript.
Original string is \'original READ ONLY\'
stringObject.replace(findstring,newstring)
I prefer the regex approach,
newstring = oldstring.replace(/regexforstringtoreplace/, 'new string');
its also worth considering the g and i regex modifiers, these do a global replace (i.e. replaces all occurrences) and makes it case insensitive.
for example:
<script type="text/javascript">
var str = "this is a String";
document.write(str.replace(/\s/g, "_"));
would print: this_is_a_string
document.write(str.replace(/s/gi, "f"));
would print "thif if a ftring"
</script>
String.replace()
is regexp-based; if you pass in a string as the first argument, the regexp made from it will not include the ‘g’ (global) flag. This option is essential if you want to replace all occurances of the search string (which is usually what you want).
An alternative non-regexp idiom for simple global string replace is:
function string_replace(haystack, find, sub) {
return haystack.split(find).join(sub);
}
This is preferable where the find
string may contain characters that have an unwanted special meaning in regexps.
Anyhow, either method is fine for the example in the question.
Good summary. It is regexp based, if you use regexp notation you can specify the i and g modifiers (case insensitive (i), which will match regardless to case and global (g), which will replace all occurences), if you use string notation it'll get converted to a regex and you wont' be able to specify any modifier.
<script type="text/javascript">
var str1="Visit Microsoft!";
var str2 = str1.replace(/microsoft/i, "W3Schools"); //Will work, per the i modifier
var str3 = "original READ ONLY";
var str4 = str3.replace("ONLY", "WRITE"); //Will also work
</script>