Julius A
Julius A

Reputation: 39652

Javascript - how to replace a sub-string?

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...

Upvotes: 14

Views: 32036

Answers (4)

bobince
bobince

Reputation: 536695

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.

Upvotes: 27

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340456

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>

Upvotes: 12

Andrew Bullock
Andrew Bullock

Reputation: 37398

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>

Upvotes: 2

rogeriopvl
rogeriopvl

Reputation: 54144

stringObject.replace(findstring,newstring)

Upvotes: 3

Related Questions