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>
Now what I want to do here is that I want the value of the txt1 which is ood to be matched in myString.
But putting the variable myWord into the myPattern like this: /.myWord/ won't work. Need help please. Many thanks
UPDATE:
I did everything as what it is in the answers but it returns wood,wood instead of wood only, I just wanted to get only 1 match. Just like using for example /.ood/ - this only returns 1 match. Please help
And also, how can I get the word wood by having only od in my input text. I just wanted this for searching..
You can use a string as a regular expression using the RegExp Object:
var myPattern = new RegExp('.'+myWord,'g');
Fiddle Example
Doing a single match in your case, is simply changed the second parameter in RegExp from g to m (which means to make one match per line for multi lines, but in this case a strings is simply all one line). For finding the word "wood" from "ood","od","d", or other cases. You can do this:
var myPattern = new RegExp("\\b\\w+"+myWord+"\\b",'m');
Note I have a solution in the comments below, but this one is better.
The items \\b ... \\b mean word boundaries. Basically ensuring that it matches a single word. Then the \\w means any valid "word character". So overall the regexp means (using myWord = "od"):
|word boundary| + (1 or more word characters) + "od" + |word boundary|
This will ensure that it matches any words in the string than end with the characters "od". Or in a more general case you can do:
var myPattern = new RegExp("\\b\\w*"+myWord+"\\w*\\b",'m');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With