Click here to Skip to main content
14,699,570 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a textarea, two inputes and a button. In textarea i write any sentence, for example "Hello, how are you". In first input i write a word, for example "you" and in second input i write replacing word, for example "they". After clicking on Replace button, i must get like this result ` "Hello, how are they". How can i do that?

What I have tried:

I have tried like this, but it's wrong :(

<fieldset>
		<legend>Replace words</legend>
		<textarea id="text3" cols="50" rows="10" placeholder="Type a sentence..."></textarea><br>
		<input id="word1" type="text" placeholder="Word 1">
		<input id="word2" type="text" placeholder="Word 2">
		<button onclick="ReplaceWord()">Replace</button>
	</fieldset>


function ReplaceWord(){
	var a = document.getElementById("text3").value;
	var b = document.getElementById("word1").value;
	var c = document.getElementById("word2").value;
	var x = a.split(" ");
	for(var i = 0; i < x.length; i++){
		if(x.indexOf(b) != -1){
			x = x.replace(b,c);
		}
	}
	document.getElementById("text3").value = x.join(" ");
}
Posted
Updated 28-Aug-20 2:04am

If you want to replace only the first occurence doing
var newText = a.replace(b, c);
document.getElementById("text3").value = newText;
will do the job.

There is no default method with a string parameter to replace multiple occurences. But the regex version can do this with the global option:
// Use a RegExp instance here to pass a string known only at runtime.
//var re = new RegExp(b, "g");
// EDIT: To match only whole words use the special character "\b" (word boundary).
var re = new RegExp("\\b" + b + "\\b", "g");
var newText = a.replace(re, c);
document.getElementById("text3").value = newText;

See also String.prototype.replace() - JavaScript | MDN[^] and Regular Expressions - JavaScript | MDN[^].
   
v2
Comments
Suren97 16-Jul-18 7:16am
   
but my condition is true?
Jochen Arndt 16-Jul-18 7:36am
   
What do you mean by "condition is true"?

What I forgot:
If you want to match only whole words enclose them with the \b (word boundary) special character.
i think its like
var x = a.split(" ").replace(b,c);

it shall be work as well.
   
Comments
Suren97 16-Jul-18 7:07am
   
Inside of condition?
Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900