How to use String.match() in javascript - 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..

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

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

Related

regex target specific character around variable

Hi,
I have this code:
var room = 'room2';
var exitroom = 'room1,room2,room3';
exitroom = exitroom.replace(/,${room},/,'');
console.log(exitroom);
you can try it here: https://jsfiddle.net/uq9w0Ls4/
my expected output is simply room1,room3 by taking room2 out but since it may change its position within the string I want to target the , no matter if it comes before or after the string but I cant figure out the regex logic here. I know I could just do simply:
var room = 'room2';
var exitroom = 'room1,room2,room3';
exitroom = exitroom.replace(room+',','').replace(','+room,'');
console.log(exitroom);
which works but I think regex would be a more direct approach.
Thank you.
First, by writing .replace(/,${room},/,'') you are not using the variable room.
To use a variable in a regex you should call new RegExp()
Second, if you want a regex that will match when the comma is before or after the word, you can use a group () with an Or | operator.
so it should look like this:
var reg = new RegExp(`(?:${room},|,${room})`, "g");
exitroom.replace(reg,'');
The ?: at the beginning of the group, is just so it should be a non-capturing group, it should work just fine also without it

searching for words starting with specific letters using JavaScript RegExp

I need to find all the words in a string array which start with m but not have m in the middle?
var arr = "Hello my mother! how is Ramy?";
I tried that:
var ragexp = new RegExp("\sm[a-z]*|^m[a-z]*", "g");
var test = regexp.test(arr); // test should be true if anything matched
i hope this will be useful for you:
\bm[^m]*?\b
I recommend this page for see more visual the expressions, just select the Flags(global, case insensitive):
enter link description here

How to create a regex that checks the string contains specific pattern in javascript?

I have a requirement where I need to traverse through the string and get the first occurrence of a specific pattern like as follows,
i am a new **point**
On the occurrence of two consecutive character it must return true.
I must *not* be returned or*
The above pattern must return false.I tried to create regex following few links but the string.match method always returns null.
My code,
var getFormat = function(event) {
var element = document.getElementById('editor');
var startIndex = element.selectionStart;
var selectedText = element.value.slice(startIndex);
var regex = new RegExp(/(\b(?:([*])(?!\2{2}))+\b)/)
var stringMatch = selectedText.match(regex);
console.log('stringMatch', stringMatch);
}
<html>
<body>
<textarea onclick='getFormat(event);' rows='10' cols='10' id='editor'></textarea>
</body>
</html>
As I am new to regex I couldn't figure out where I am wrong.Could anyone help me out with this one?
On the occurrence of two consecutive character it must return true.
If I'm understanding you correctly. You just want to check if a string contains two consecutive characters, no matter which character. Then It should be enough doing:
(.)\1
Live Demo
This is of course assuming that it's literally any character. As in two consecutive whitespaces also being a valid match.
If you just need to check if there's two stars after each other. Then you don't really need regex at all.
s = "i am a new **point**";
if (s.indexOf("**") != -1)
// it's a match
If it's because you need the beginning and end of the two stars.
begin = s.indexOf("**");
end = s.indexOf("**", begin + 1);
Which you with regex could do like this:
((.)\2)(.*?)\1
Live Demo

Javascript regex how to get all occurences between two words in a string

I am using the following function in order to get the string between two words in a string:
function findStringBetween(str,first,last){
var r = new RegExp(first+'.*(.*)'+last,'gm');
var a = str.match(r);
return a;
}
But I can not get all occurences of the possible findings.
For example if a sentence (str) like this is the case:
"The sentence which has a lot of words inside. The sentence short inside. And some other sentence to fill this example of mine."
I get this:
var found = findStringBetween(str, 'The', 'inside');
>> ["The sentence which has a lot of words inside. The sentence short inside"]
What I'd like to get is all occurances of findings between the two words "The" and "inside". For the example result would be:
>> ["The sentence which has a lot of words inside",
>> "The sentence short inside"]
Is this possible via regex? if it is not, what can I do to make a fast finding?
Thanks
Yes, it's possible. The problem is that the regex character "*" (and "+") is "greedy" by default, meaning it will go with the longest possible match. You want the shortest possible match, so make it "lazy" by adding a "?" after it, like so:
function findStringBetween(str, first, last) {
var r = new RegExp(first + '(.*?)' + last, 'gm');
return str.match(r);
}

javascript regex string template extract variable

I'm doing kind of a reverse templating thing, I have a string, and I know the template used to generate it, I want to get the variable value.
For example:
URL: http://c.tile.osm.org/24/7881145/7385476.png
Template: http://{s}.tile.osm.org/{z}/{x}/{y}.png
I would like to get the zoom level ({z}) from the tile's URL, in this case 24. This exact Template url will not always be used (it varies based on what basemap is used, etc.), but I'll always be looking for the {z} value.
It looks like blint may have beat me to it, but essentially what you want to do is generate a regular expression from your template and execute it:
function zFromTemplate(str, template) {
var sr = template.replace("?", "\\?")
.replace(/\{[^z]\}/g, ".*?")
.replace(/\{z\}/g, "(.+)");
var rex = new RegExp(sr),
parts = rex.exec(str);
if(parts) {
return parts[1];
}
return null;
}
And here's a codepen demonstrating it's use. If nothing else it's a little more succinct than the originally accepted answer.
You can capture values using a regex. This thread is similar to your case, and here would be your solution:
var myString = "http://c.tile.osm.org/24/7881145/7385476.png";
var myRegexp = /http:\/\/[A-z]\.tile\.osm\.org\/([0-9]+)\/([0-9]+)\/([0-9]+)\.png/;
var match = myRegexp.exec(myString);
alert(match[1]); // 24
And here's the fiddle: http://jsfiddle.net/2sx4t/
EDIT:
Following to your comment, here's the most flexible code I could quickly provide you: http://jsfiddle.net/2sx4t/4/
var myString = "http://c.tile.osm.org/24/7881145/7385476.png";
var myTemplate = "http://{s}.tile.osm.org/{z}/{y}/{x}.png";
var myString2 = "//tiles.arcgis.com/tiles/c/arcgis/rest/services/TimeZones/MapServer/tile/223774/24/2636";
var myTemplate2 = "//tiles.arcgis.com/tiles/{s}/arcgis/rest/services/TimeZones/MapServer/tile/{x}/‌{z}/{y}";
var z = extractToken(myTemplate, myString, '{z}');
alert(z); // 24
var z2 = extractToken(myTemplate, myString, '{z}');
alert(z2); // 24
The tricks in this code is the combination of the use of template.indexOf(m) to be able to find the order of your tokens and String.replace() to generate the appropriate RegExp.
Note that I shuffled the order of the tokens in myTemplate2and that it sill works.
Don't expect magic from RegExp, magic is in our brains ;-)
Bonus with map return, independantly of other tokens: http://jsfiddle.net/2sx4t/8/
Well, if you're sure that the {z} parameter is the only 1 or 2 digits element in your URL, you can try with regexp:
var myRegexp = /.*\/([0-9]{1,2})\/.*/;
This would match the last occurrence of any one or two digits enclosed in two slashes (/1/, /24/, ...)

Categories

Resources