javascript 检查 TextArea/TextBox 是否包含某个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25167909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:06:07  来源:igfitidea点击:

Check if TextArea/TextBox contains a certain String

javascript

提问by Sad CRUD Developer

Given textarea is a textarea element with id 'textareabox', how can I check if it contains a string within it?

鉴于 textarea 是一个 ID 为“textareabox”的 textarea 元素,我如何检查它是否包含一个字符串?

var textarea = document.getElementById('textareabox');

var word = something;

if (!textarea.contains(word))
{
textarea.value += word;
}

回答by nsthethunderbolt

You can use .value, as:

您可以使用.value, 作为:

var textarea = document.getElementById('textareabox');

var word = 'something';

var textValue=textarea.value;  //-> don't use .innerHTML since there is no HTML in a textarea element

if (textValue.indexOf(word)!=-1)
{
  alert('found')
}

回答by pattmorter

You could do something like this:

你可以这样做:

var textarea = document.getElementById('textareabox').value;

if (texarea.match(word) != null) {
    // do some stuff
}

A better regex than what I did but I don't know regex all that well (forgive me regex ignorance).

一个比我做的更好的正则表达式,但我不太了解正则表达式(原谅我对正则表达式的无知)。

回答by Jsscripter

body {
background-color: red;


}
<html>
<h1>#mywebsite</h1>
<body>1+1=2?(yes <strong>or</strong> no)</body>
<input type="text" id="text" placeholder="text here"></input>
<button type="button" id="u" onclick="run()">submit</button>
<script type="text/javascript">


var a = 1;
function run() {
if (document.getElementById("text").value.includes("yes")) {
alert("correct!");
/*if the textbox includes "yes" it will say you got it right; basically whatever the input your user puts into the textbox it will test if the users sentence contains "yes" it alerts "correct!" into html if its wrong well it alerts "Try again!" the thing is, no matter what, if yes is in the sentance it will still say its correct.*/
/*if the snippet will not work use a different website to put code on */
document.body.innerHTML += "<li>attempt #" + a + ": correct";
a++
}
 
else {

alert("try again!")
document.body.innerHTML += "<li>attempt #" + a + ": try again";
a++
}



}
</script>