Reputation: 723
I am working with javascript and I have created a jsfiddle.
I have two textfields: one contains user input and the other one contains result. My problem is when I enter the same word twice then only one of them gets replaced.
For example, if I enter "going,going"
in the first text field then the result is "GNG,going"
- instead of "GNG,GNG"
. What am I doing wrong in my code?
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Scrolling DIV demo on iPhone / iPod Touch / Android / iPad</title>
</head>
<body>
<input type="text" id="first_text" value="going, used to, to do fast, as soon as possible"/>
<input type="text" id="second_text"/>
<input type="button" onclick="replaceText()" value="Click!"/>
</body>
</html>
Javascript:
var replaceText = function () {
var inputval = document.getElementById('first_text').value;
var arr = {
"going": "GNG",
"used to": "UD",
"as soon as possible": "ASAP",
"to do fast": "tdf"
}
for(var key in arr) {
if (typeof (arr[key]) !== "undefined") inputval = inputval.replace(key, arr[key])
}
document.getElementById("second_text").value = inputval;
}
Upvotes: 1
Views: 94
Reputation: 69934
Replace only replaces the first occurence of the pattern. If you want to replace more then once you will need to use the regexp version of the code. (note the "g" standing for "global replace")
'going, going'.replace(/going/g, 'Go'); // 'Go, Go'
You can dinamically create a regexp from a string if you still want to keep the same code (instead of rewriting it to use regexp patterns directly)
var pattern = new RegExp('going', 'g');
But then you must not have regexp special chars in your pattern. If you want to be able to use special characters, like parenthesis or backslashes, in the key you will need an escape function, like the following one:
function regex_escape(str){
return str.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1');
}
var pattern = new RegExp (regex_escape(key), 'g');
Upvotes: 1
Reputation: 3144
thats because replace just does the operation on the first occurence instead you can use the following :
function replaceAll(txt, replace, with_this) {
return txt.replace(new RegExp(replace, 'g'),with_this);
}
http://naspinski.net/post/Javascript-replaceAll-function.aspx
Upvotes: 1
Reputation: 37516
Change:
inputval = inputval.replace(key, arr[key])
To:
inputval = inputval.replace(new RegExp(key, 'g'), arr[key])
The replace
function and regular expressions are not global, by default, that's what the g
switch does. Working example here: http://jsfiddle.net/NSy8P/1/
Upvotes: 3