developer747
developer747

Reputation: 15938

javascript replace function only replaces the first occurance

document.getElementById("Message").innerHTML=document.getElementById("Message").innerHTML.replace("'","%%");

The above statement replaces only the first occurrence of the single quote. Could it be because that I do a submit right after that, and that javascript doesn't wait for the previous statement to be completed before moving on to the next one?

Upvotes: 1

Views: 1822

Answers (5)

Pete
Pete

Reputation: 2558

You should use a regular expression and the /g (global) flag. This will replace all occurrences:

document.getElementById("Message").innerHTML=
    document.getElementById("Message").innerHTML.replace(/'/g,"%%");

http://www.w3schools.com/jsref/jsref_replace.asp

Upvotes: 0

Alberto De Caro
Alberto De Caro

Reputation: 5213

Use the Global (g) flag in the replace() parameters.

See here

Upvotes: 0

Anoop
Anoop

Reputation: 23208

You should use regular expression in replace.

document.getElementById("Message").innerHTML=document.getElementById("Message").innerHTML.replace(/'/g,"%%");

jsfiddle

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try using regex /g

.replace(/'/g,"%%")

Change your code as below,

document.getElementById("Message").innerHTML = 
                  document.getElementById("Message")
                          .innerHTML
                          .replace(/'/g,"%%");

Upvotes: 3

iivel
iivel

Reputation: 2576

To replace globally in javascript you need to add /g to the replacement string.

See this SO link How to replace all dots in a string using JavaScript

Upvotes: 0

Related Questions