Makudex
Makudex

Reputation: 1082

How to use String.match() in javascript

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..

Upvotes: 3

Views: 2515

Answers (2)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

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'); 

Upvotes: 3

Carsten Massmann
Carsten Massmann

Reputation: 28236

Create a Regexp object like

new RegExp('.ood','g');

like in

var searchstring='ood' // this is the one you get in a variable ...

var myString = "How much wood could a wood chuck chuck";
var myPattern=new RegExp('.'+searchstring,'gi');
var myResult = myString.match(myPattern);

Upvotes: 2

Related Questions