- 用户输入 2 个字符串
- 使用正则表达式搜索第二个字符串 第一个字符串。
这些是我要遵循的指示。没有人告诉我如何处理搜索结果,因此我决定使用 exec() 方法来显示结果。
我的代码不显示任何结果。
html:
<div id="string_search">
<h3>Requirement #1</h3>
<p>Enter a string in the first box. <br>
Enter a search term in the second box.<br>
Click the button to find the term.</p>
<textarea id="user_string" rows="4" cols="50" placeholder="Enter string (text) here."></textarea>
<form>
Enter Search Term:<input type="text" id="search_term" size="45"><br>
<input type="button" id="search_button" value="Search" onclick="SearchString()"><br>
</form>
<textarea id="search_results" placeholder="Results here..." rows="4" cols="30"></textarea>
</div>
javascript:
function SearchString(){
var user_string = document.getElementById("user_string").innerHTML;
var search_term = document.getElementById("search_term").value;
// regex to find all instances of search term
var re = new RegExp(search_term,"gi");
//use exec() to return matched text
var result = re.exec(user_string);
//display results in textarea "search_results"
document.getElementById("search_results").innerHTML = result;
}
我没有收到控制台错误,是我的代码不起作用吗?也许有一个我没有看到的拼写错误或类似错误。关注这个有一段时间了,
最佳答案
工作正常,你有一些错误。
function SearchString(){
var user_string = document.getElementById("user_string").value;
var search_term = document.getElementById("search_term").value;
// regex to find all instances of search term
var re = new RegExp(search_term,"gi");
//use exec() to return matched text
var result = re.exec(user_string);
//display results in textarea "search_results"
document.getElementById("search_results").innerHTML = result;
}
您应该使用value
而不是innerHTML
的任何输入元素
关于javascript - 在 javascript 中使用 exec() 和正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32470106/