Beginner JavaScript variables - javascript

It's my first time using Java Script....
What does this do?
var INTEGER_SINGLE = /\d+/;
What does the forward slashes tell you? How about the backslash? d means for digit?
Thanks!

That creates a regular expression that matches one or more digits.
Anything inside / / is a regular expression. \d matches a digit, and + is the positive closure, which means one or more.
Having said that, depending on what this regex is supposed to do, you may want to change it to:
var INTEGER_SINGLE = /^\d+$/;
^ matches the beginning of the string, and $ the end. The end result would be that any strings you try to match against the regex would have to satisfy it in the string's entirety.
var INTEGER_SINGLE = /^\d+$/;
console.log(INTEGER_SINGLE.test(12)); //true
console.log(INTEGER_SINGLE.test(12.5)); //false
Of course if the regex is supposed to only match a single integer anywhere in the string, then of course it's perfect just the way it is.

Related

Javascript - Regular Expression with string template followed by 4 digits number?

Good day. I wanna detect the url string in the <a> tag
Link
whether it matchs the pattern : ?post_type=tribe_events&p=#### (#### = 4 digits number)
I'm writing some Jquery code to detect the expression but the console is throwing the error :
Invalid regular expression: /^(?)post_type=tribe_events&p=^(d{4})/:
Invalid group
var str = $(a).attr("href");
var regexEx = /^(?)post_type=tribe_events&p=^(d{4})/;
var ok = regexEx.exec(str);
console.log(ok);
I'm not good at the regex so I'd be aprreciated if there's any help.
There are couple of issues in your regex.
You need to remove ^ from your regex which denotes start of string and in your case your string doesn't actually start from a ? and is in middle of the string.
You need to escape ? as it has special meaning in regex which is zero or one occurrence of a character.
You need to remove second ^ after p= which isn't needed
You need to write \d and not just d for representing a number.
Also you don't need to group ? and \d{4} unless you really need them.
You corrected regex becomes,
\?post_type=tribe_events&p=\d{4}
Demo
If the test is really what you want, I suppose the right syntax would be:
/^\?post_type=tribe_events&p=\d{4}/

Why does this regular expression evaluate to false in javascript?

I'm looking for a string that is 0-9 digits, no other characters.
This is alerting me with a "false" value:
var regex = new RegExp('^[\d]{0,9}$');
alert(regex.test('123456789'));
These return true, and I understand why (The ^ and $ indicate that the whole string needs to match, not just a match within the string) :
var regex = new RegExp('[\d]{0,9}');
alert(regex.test('123456789'));
-
var regex = new RegExp('[\d]{0,9}');
alert(regex.test('12345678934341243124'));
and this returns true:
var regex = new RegExp('^[\d]{0,9}');
alert(regex.test('123456789'));
So why, when I add the "$" at the end would this possibly be failing?
And what do I need to do to fix it?
When you use
var regex = new RegExp('^[\d]{0,9}$');
syntax, you'll get regex as
/^[d]{0,9}$/
Note the \d is turned into d.
This regex /^[d]{0,9}$/ will match only the d zero to nine times.
RegExp uses string to define regex, the \ is also used as escape symbol in the string, so \ in \d is considered as the escape character.
Escape the \ by preceding it with another \.
var regex = new RegExp('^[\\d]{0,9}$');
I'll recommend you to use regex literal syntax rather than the confusing RegExp syntax.
var regex = /^\d{0,9}$/;
EDIT:
The reason you get true when using var regex = new RegExp('^[\d]{0,9}'); is because the regex implies that the string should start with any number of d include zero to nine. So, event when the string does not starts with d the condition is stratified because of 0 as the minimum no of occurrences.
You might want to check if the string starts with one to nine digits.
var regex = /^\d{1,9}$/;
You should use the regular expression literal (without quotes and using the beginning and ending slashes) when defining the RegExp object. This is the recommended approach when the regular expression will remain constant, meaning it does not need to be compiled every time it is used. This gives you the desired result:
var regex = new RegExp(/^[\d]{0,9}$/);
Because $ means End of line, and your string does not have an end of line as last character
May be you are looking for "\z"

JavaScript and regular expressions: get the number of parenthesized subpattern

I have to get the number of parenthesized substring matches in a regular expression:
var reg=/([A-Z]+?)(?:[a-z]*)(?:\([1-3]|[7-9]\))*([1-9]+)/g,
nbr=0;
//Some code
alert(nbr); //2
In the above example, the total is 2: only the first and the last couple of parentheses will create grouping matches.
How to know this number for any regular expressions?
My first idea was to check the value of RegExp.$1 to RegExp.$9, but even if there are no corresponding parenthseses, these values are not null, but empty string...
I've also seen the RegExp.lastMatch property, but this one represents only the value of the last matched characters, not the corresponding number.
So, I've tried to build another regular expression to scan any RegExp and count this number, but it's quite difficult...
Do you have a better solution to do that?
Thanks in advance!
Javascripts RegExp.match() method returns an Array of matches. You might just want to check the length of that result array.
var mystr = "Hello 42 world. This 11 is a string 105 with some 2 numbers 55";
var res = mystr.match(/\d+/g);
console.log( res.length );
Well, judging from the code snippet we can assume that the input pattern is always a valid regular expression, because otherwise it would fail before the some code partm right? That makes the task much easier!
Because We just need to count how many starting capturing parentheses there are!
var reg = /([A-Z]+?)(?:[a-z]*)(?:\([1-3]|[7-9]\))*([1-9]+)/g;
var nbr = (' '+reg.source).match(/[^\\](\\\\)*(?=\([^?])/g);
nbr = nbr ? nbr.length : 0;
alert(nbr); // 2
And here is a breakdown:
[^\\] Make sure we don't start the match with an escaping slash.
(\\\\)* And we can have any number of escaped slash before the starting parenthes.
(?= Look ahead. More on this later.
\( The starting parenthes we are looking for.
[^?] Make sure it is not followed by a question mark - which means it is capturing.
) End of look ahead
Why match with look ahead? To check that the parenthes is not an escaped entity, we need to capture what goes before it. No big deal here. We know JS doens't have look behind.
Problem is, if there are two starting parentheses sticking together, then once we capture the first parenthes the second parenthes would have nothing to back it up - its back has already been captured!
So to make sure a parenthes can be the starting base of the next one, we need to exclude it from the match.
And the space added to the source? It is there to be the back of the first character, in case it is a starting parenthes.

Regex to find last token on a string

I was wondering if there is a way having this
var string = "foo::bar"
To get the last part of the string: "bar" using just regex.
I was trying to do look-aheads but couldn't master them enough to do this.
--
UPDATE
Perhaps some examples will make the question clearer.
var st1 = "foo::bar::0"
match should be 0
var st2 = "foo::bar::0-3aab"
match should be 0-3aab
var st3 = "foo"
no match should be found
You can use a negative lookahead:
/::(?!.*::)(.*)$/
The result will then be in the capture.
Another approach:
/^.*::(.*)$/
This should work because the .* matches greedily, so the :: will match the last occurence of that string.
Simply,
/::(.+)$/
You can't use lookaheads unless you know exactly how long a string you're trying to match. Fortunately, this isn't an issue, because you're only looking at the end of the string $.
I wouldn't use regular expressions for this (although you certainly can); I'd split the string on ::, since that's conceptually what you want to do.
function lastToken(str) {
var xs = str.split('::');
return xs.length > 1 ? xs.pop() : null;
}
If you really want just a regular expression, you can use /::((?:[^:]|:(?!:))*)$/. First, it matches a literal ::. Then, we use parentheses to put the desired thing in capturing group 1. The desired thing is one or more copies of a (?:...)-bracketed string; this bracketing groups without capturing. We then look for either [^:], a non-colon character, or :(?!:), a colon followed by a non-colon. The (?!...) is a negative lookahead, which matches only if the next token doesn't match the contained pattern. Since JavaScript doesn't support negative lookbehinds, I can't see a good way to avoid capturing the :: as well, but you can wrap this in a function:
function lastTokenRegex(str) {
var m = str.match(/::((?:[^:]|:(?!:))*)$/);
return m && m[1];
}
var string2 = string.replace(/.*::/, "");
though perhaps string isn't the best choice of name for your string?

Removing Numbers from a String using Javascript

How do I remove numbers from a string using Javascript?
I am not very good with regex at all but I think I can use with replace to achieve the above?
It would actually be great if there was something JQuery offered already to do this?
//Something Like this??
var string = 'All23';
string.replace('REGEX', '');
I appreciate any help on this.
\d matches any number, so you want to replace them with an empty string:
string.replace(/\d+/g, '')
I've used the + modifier here so that it will match all adjacent numbers in one go, and hence require less replacing. The g at the end is a flag which means "global" and it means that it will replace ALL matches it finds, not just the first one.
Just paste this into your address bar to try it out:
javascript:alert('abc123def456ghi'.replace(/\d+/g,''))
\d indicates a character in the range 0-9, and the + indicates one or more; so \d+ matches one or more digits. The g is necessary to indicate global matching, as opposed to quitting after the first match (the default behavior).

Categories

Resources