Javascript:如何替换textarea中的单词 [英] Javascript: how to replace word in textarea
问题描述
我有一个textarea,两个inpute和一个按钮。在textarea我写任何句子,例如你好,你好吗。在第一个输入中,我写了一个单词,例如你,在第二个输入中我写了替换单词,例如他们。点击替换按钮后,我必须得到这样的结果你好,他们是怎么回事。我怎么能这样做?
我的尝试:
我试过这样,但是错了:(
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(" ");
}
推荐答案
如果你想只替换第一次出现
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;
另见 String.prototype.replace() - JavaScript | MDN [ ^ ]和正则表达式 - JavaScript | MDN [ ^ ]。
我认为它像
i think its like
var x = a.split(" ").replace(b,c);
它也可以正常工作。
it shall be work as well.
这篇关于Javascript:如何替换textarea中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!