Javascript Regex plus operator usage [duplicate] - javascript

This question already has answers here:
How do I match an entire string with a regex?
(8 answers)
What is the meaning of + in a regex?
(5 answers)
Closed 6 months ago.
So I've read a lot of posts and documentation on the + operator for JS regex, but I'm still unsure of what it wouldo do.
For example, one of the websites I looked after gave the following example:
const nums = /\d+/
console.log(nums.test('456'))
Says it would look for infinite possibilites for d. But then...
const nums = /\d/
console.log(nums.test('456'))
... has the same result.
So I tried using numbers... for instance:
const nums2 = /45/
const nums 3 = /45+/
console.log(....
But testing both regex would STILL give the same result. If I put any numbers before or after 45 with or without the + it will still give me a "true" if 45 is togheter.
So can someone explain what the + symbol in regex means and it's usage in a way I can understand?

There's no difference in the cases you tried -- if there's one digit, then there's also one or more digit, so they both match.
But if you use it together with other patterns you can have a difference.
console.log(/A\dB/.test("A123B"));
console.log(/A\d+B/.test("A123B"));
The first one is false because it only matches a single digit between A and B; the second is true because it matches any number of digits.
The difference can also be useful if you use .match() instead of .test(). This returns the part of the string that matched the regexp, and \d+ will return the entire number, while \d will just return the first digit.

Related

Adding a length to a regex expression [duplicate]

This question already has an answer here:
Restricting character length in a regular expression
(1 answer)
Closed 3 years ago.
Im trying to add a length requirement to the below code.
Code: ^[a-zA-z0-9\!\$\%\&]+(?: [a-zA-z0-9\!\$\%\&]+)*$
I want a sentence with spaces to only have around 1 to 10 characters. I want to count spaces as well. The code provided doesn't allow leading or trailing space but space between.
A sentence limited to 10 chars is obscenely small but you can use:
^(?=^.{1,10}$)[a-zA-z0-9\!\$\%\&]+(?: [a-zA-z0-9\!\$\%\&]+)*$
(?=^.{1,10}$) = ensure that between 1 and 10 chars exist between the start and end of the string.
https://regex101.com/r/zsa1N9/1
I see your new comment about Javascript. You would be better off adding a check for .length in addition to your regex.

JS Regex: (a|b) Matches the a or the b part of the subexpression. Different behaviour when a and b switched [duplicate]

This question already has answers here:
Why does the order of alternatives matter in regex?
(1 answer)
Why order matters in this RegEx with alternation?
(3 answers)
Closed 3 years ago.
I am trying to replace 2% with ''(empty) using regexp concept. If input string is either % or 2%, it should be replaced with ''(empty):
const str = "2%";
console.log(`2%`.replace(/^\d%$|\d(?=%)/, ''));
console.log(`2%`.replace(/\d(?=%)|^\d%$/, ''));
(a|b) Matches the a or the b part of the subexpression.
"2%".replace(/^\d%$|\d(?=%)/, ''). This works well.
But, "2%".replace(/\d(?=%)|^\d%$/, '') does not.
The difference is in what the regex tries to match first. The left expression takes precedence. The right is only tried when the left one fails to match.

What's the best way to extract prices from string in one line? [duplicate]

This question already has answers here:
Simple regular expression for a decimal with a precision of 2
(17 answers)
Closed 6 years ago.
What's the best way to extract numbers (with dot in between sometimes)from string in one line?
var str = "ghjkhjgbkhj123.45khgbkhjgk67 8kjhgkj hg13.99sads";
I need an array of [123.45, 67, 8, 13.99];
str.match(/\d+/g) returns slightly different results - it doesn't count ".".
Use regex as /\d+(?:\.\d+)?/g
var str = "ghjkhjgbkhj123.45khgbkhjgk67 8kjhgkj hg13.99sads";
console.log(
str.match(/\d+(?:\.\d+)?/g)
);
Regex explanation here.
str.match(/[.\d]+/g) will do what you are asking for. It will allow for more than one dot, so if you want to do something "sensible" given 123.456.789 you will probably want something more complicated -- but in that case you should first figure out exactly what more sensible thing you want.

Javascript: regular expression and .test [duplicate]

This question already has answers here:
How do you use the ? : (conditional) operator in JavaScript?
(20 answers)
Closed 6 years ago.
I'm new to JS - this might be easy for you guys to answer. I've been reading on regular expression but couldn't figure out the full meaning of this code:
I've been asked to write a myParseInt method with the following rules:
It should make the conversion if the given string only contains a
single integer value (and eventually spaces - including tabs, line
feeds... - at both ends).
For all other strings (including the ones representing float values),
it should return NaN.
It should assume that all numbers are not signed and written in base
10.
The answer is:
function myParseInt ( str ) { return /^\s*\d+\s*$/ . test (str) ? + str : NaN; }
(please correct me if I'm wrong!) But I sort of understand the first and last part (/^\s* and \s*$) where it matches the beginning and end of str input with white space character. The \d+ part matches digit characters 1 or more times.
The .test(str) part matches the str with the stated regular expressions and gives it a true or false value -
but why is there ? after .test(str), then + str: NaN;? I am unsure what does the ? do, the : syntax. I know it has something to do with if it doesn't match, gives NaN. But I am trying to get clarifications regarding the syntax which I couldn't find on MDN.
Many thanks!
The ? is a ternary operation.
You write a condition that returns true/false followed by a question mark, then what to return for truthy and falsy.
It is taken from C.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

What is the most compact, efficient and reliable way of extracting numbers from dollar amounts in JavaScript? [duplicate]

This question already has answers here:
How to convert a currency string to a double with Javascript?
(23 answers)
Closed 7 years ago.
What I'm talking about is reading a string into a Number, e.g.
"$107,140,946" ---> 107140946
"$9.99" ---> 9.99
Is there a better way than
dolstr.replace('$','');
dolstr.replace(',','');
var num = parseInt(dolstr,10);
???
Using regex is much simpler to read and maintain
parseFloat(dolstr.replace(/\$|,/g, ""));
You can just put all of this in oneliner:
parseFloat(dolstr.replace('$','').split(",").join(""))
Notice that I do not replace the second one, because this will remove just the first ','.
Using a simple regex and the string's replace function
parseFloat(dolstr.replace(/[^\d\.]/g, ''))
Breakdown
It replaces every instance of a character that is not a digit (0 - 9) and not a period. Note that the period must be escaped with a backwards slash.
You then need to wrap the function in parseFloat to convert from a string to a float.
Assuming input is always correct, just keep only digits (\d) and the dot (\.) and get rid of other characters. Then run parseFloat on the result.
parseFloat(dolstr.replace(/[^\d\.]/g, ''))

Categories