I have this code here:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Display the result here.</p>
<input type = "text" value = "ood" id = "txt1"/>
<script>
var myString = "How much wood could a wood chuck chuck";
var myWord = document.getElementById("txt1").value; // ood
var myPattern = /.myWord/; // I want this to be /.ood/
var myResult = myString.match(myPattern);
document.getElementById("demo").innerHTML = myResult;
</script>
</body>
</html>
现在我想做的是将
txt1
的值(ood
)与myString
匹配。但是像这样将变量myWord
放入myPattern
中:/.myWord/
是不行的。需要帮忙。非常感谢。更新:
我按照答案中的步骤做了一切,但它返回的是
wood,wood
而不是只有wood
,我只想得到一个匹配项。就像使用/.ood/
一样,这只返回一个匹配项。请帮忙解决。此外,如果我只有输入文本中的
od
,如何获得单词wood
。我只想用于搜索。
var myPattern = new RegExp('\.' + myWord, 'gi');
- Tushar