检查TextArea / TextBox是否包含某个String

时间:2014-08-06 18:48:06

标签: javascript

鉴于textarea是一个带有id'textareabox'的textarea元素,我如何检查它是否包含一个字符串?

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

var word = something;

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

3 个答案:

答案 0 :(得分:3)

您可以使用.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')
}

答案 1 :(得分:1)

你可以这样做:

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

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

比我做的更好的正则表达式,但我不能很好地了解正则表达式(请原谅我的正则表达式无知)。

答案 2 :(得分:0)

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>