views:

4534

answers:

5

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'

I want to replace the 'READ ONLY' with 'READ WRITE'

Any quick answer please? Possibly with a javascript code snippet...

+7  A: 

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>
Vinko Vrsalovic
str2 = str2.replace(/^Visit/, 'Don't visit');
Gareth
Works for me. thanks very much!
J Angwenyi
bobince's answer is the more correct; this answer implies that passing a string is not the same as the regex, but as bobince indicates, either way it is used as a regex.
Jason Bunting
+2  A: 
stringObject.replace(findstring,newstring)
rogeriopvl
+1  A: 

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>
Andrew Bullock
+12  A: 

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.

bobince
This is really useful, TY!
CommanderZ
A: 

Hi i have a string like this strPath="\\\a\t\r\n\x\y. i need to replace "\" with "\\\". So the final string should be \\\\\\\a\\\t\\r\\\n\\\x\\\y. How to do this?.