Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 247
Julius A Avatar asked Oct 31 '08 09:10

Julius A


People also ask

How do you replace a substring?

You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement).

How do you replace a certain part of a string JavaScript?

JavaScript replace() Method: We can replace a portion of String by using replace() method. JavaScript has an inbuilt method called replace which allows you to replace a part of a string with another string or regular expression. However, the original string will remain the same.

How do you substitute in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

How do you replace a character in a string in JavaScript without using replace method?

To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.


1 Answers

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.

like image 121
bobince Avatar answered Oct 03 '22 07:10

bobince