searching for words starting with specific letters using JavaScript RegExp - javascript

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

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

Hide Div based on search content and text value in div

Hi firstly ty for looking at my code ^^
i have made a working example that hides the content based on the input but the problem is it looks letter for letter so lets say i have this text in my div "yes i know" i have yo start typing with the y to find it because if i type lets say "know" it wont find it
here is the example demo
and here is my code
I would like it to work that it would look for words in stead exact letter it starts
tyvm in advance ^^
$('#my-textbox').keyup(function() {
var value = $(this).val();
var exp = new RegExp('^' + value, 'i');
$('.panel-group .panel').each(function() {
var isMatch = exp.test($('.accordion-toggle', this).text());
$(this).toggle(isMatch);
});
});
simply remove the ^ from the RegExp. this means it has to start with said string
var exp = new RegExp(value, 'i');
On this link you can find more info about RegExp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

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

How do I get a list of strings ending in a newline or ending in the end of the string in javascript regex?

I'm pretty frustrated with regex right now. Given:
var text = "This is a sentence.\nThis is another sentence\n\nThis is the last sentence!"
I want regex to return to me:
{"This is a sentence.\n", "This is another sentence\n\n", "This is the last sentence!"}
I think i should use
var matches = text.match(/.+[\n+\Z]/)
but \Z doesn't seem to work. Does javascript have an end of string matcher?
You can use the following regex.
var matches = text.match(/.+\n*/g);
Working Demo
Or you could match a newline sequence "one or more" times or the end of the string.
var matches = text.match(/.+(?:\n+|$)/g);
Try this one: /(.+\n*)/g
See it here: http://regex101.com/r/wK8oX3/1
If you wanted an array and didn't want to keep the "\n" around you could do...
var strings = text.split("\n");
which would yield
["This is a sentence.", "This is another sentence", "", "This is the last sentence!"]
if you wanted to get rid of that empty string chain a filter onto the split...
var strings = text.split("\n").filter(function(s){ return s !== ""; });
Maybe not what you want tho, also not as efficient as the regex options already proposed.
Edit: as torazaburo pointed out using Boolean as the filter function is cleaner than a callback.
var strings = text.split("\n").filter(Boolean);
Edit Again: I keep getting one upped, using the /\n+/ expression is even cooler.
var strings = text.split(/\n+/);
To get an array of sentences:
var matches = text.match(/.+?(?:(?:\\n)+|$)/g);
You can try this,
text.match(/.+/g)

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