How to build a regex w/ new RegExp() [duplicate] - javascript

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 6 years ago.
Have an array of local storage keys that looks something like this
[
'$gl-user',
'$gl-date-preference::22'
'$gl-date-preference::28'
'$gl-mg-filters::22::1'
'$gl-mg-filters::22::8'
]
First ::_number_ represents the storeId.
Second ::_number_ can
represents any additional identifier.
Trying to build a function that takes a storeId and returns all keys that match that storeId. So if 22 was passed in to that function it would return
[
'$gl-date-preference::22',
'$gl-mg-filters::22::1',
'$gl-mg-filters::22::8'
]
Here is my first attempt. Copying this into the console returns null every time but I do not understand why.
var regex = new RegExp('^[$\w\d\-]+\:\:' + '22');
'$gl-mg-filters::22'.match(regex);
Any assistance in getting this regex to work, or ideas on a better solution would be greatly appreciated. Thank you!

Your regex isn't matching, because you're only escaping with the slashes inside of the string. Instead, you should be escaping it twice, e.g.:
var regex = new RegExp('^[$\\w\\d\\-]+\\:\\:' + '22');
'$gl-mg-filters::22'.match(regex);
Your initial attempt would try to compile ^[$wd-]+::22 into a Regex.

Related

How to exclude certain string values via regex? [duplicate]

This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
Closed 3 years ago.
I am a beginner when it comes to regex. I have string cn=foo,ou=bar,ou=zoo,ou=aa,ou=bb,ou=cc,ou=dd,o=someOrg,c=UK. I need to get foo,bar and zoo so I used following regex to extract string in javascript.
const dn = 'cn=foo,ou=bar,ou=zoo,ou=aa,ou=bb,ou=cc,ou=dd,o=someOrg,c=UK';
const regex = /^cn=(\w+),ou=(\w+),ou=(\w+)/;
const found = dn.match(regex);
console.log(found) --> Array ["cn=foo,ou=bar,ou=zoo", "foo", "bar", "zoo"]
Then ou=bar value is changed upon new requirement to ou=bar - 1. It could have - or numeric value in any order within that string value. I tried following regex.
const regex = /^cn=(\w+),ou=(.+),ou=(\w+)/;
however it returns unwanted data Array ["cn=foo,ou=bar,ou=zoo,ou=aa,ou=bb,ou=cc,ou=dd", "foo", "bar,ou=zoo,ou=aa,ou=bb,ou=cc", "dd"]
What I expect is Array ["cn=foo,ou=bar - 1,ou=zoo", "foo", "bar - 1", "zoo"]. I tried to exclude unwanted data via ^(ou=aa|ou=bb|ou=cc|ou=dd|o=someOrg|c=UK) within the regex but I got null value. I'd appreciate someone can help me to correct regex syntax.
Update:
I tried /^cn=(\w+),ou=(\w+\s+-\s+\d+),ou=(\w+)/ but this covers it above example but it won't cover something like ou=bar-1 or ou=1bar-..
The easies way to solve this task is to make it non-greedy (notice the question mark!):
const regex = /^cn=(\w+),ou=(.+?),ou=(\w+)/;
Alternatively, you may want to exclude the comma:
const regex = /^cn=(\w+),ou=([^,]+),ou=(\w+)/;

NodeJS Regex match 4 digit number in string with 'OR' words [duplicate]

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 3 years ago.
I need to regex string with a year inside. Template is 'Year-<4 digits>-"high OR low"-level'.
I've built this regex: /Year-\d{4}-\b(low|high)\b-level/gi;
In online regex testers my strings pass the check. Sample code:
const template = /Year-\d{4}-\b(low|high)\b-level/gi;
const txtArr = ['Year-2019-low-level', 'Year-2019-high-level', 'Year-low-level', 'Year-high-level', 'Year-2018-low-level', 'Year-2018-low-level']
for (const s of txtArr) {
console.log(template.test(s), s);
}
I expect 2 of sample strings to not pass, but 4 should pass. But they dont - only 2 of them pass. Also in browser console they don't pass. Tried in FF and Chrome. Can't understand why.
Also, if I copy the string that is not passing the match and just make
console.log(template.test('Year-2018-low-level'), 'Year-2018-low-level');
it passes! I've got only one idea: looks like in every iteration of loop something is not reset in regex, and it keeps something in memory, that is not letting match pass.
P.S. I even copied the same string which must pass the test to array, like that:
const txtArr = ['Year-2019-low-level', 'Year-2019-low-level', 'Year-2019-low-level', 'Year-2019-low-level', 'Year-2019-low-level', 'Year-2019-low-level']
and the results are true-false-true-false-true... Why? And how to fix?
I found an explanation here: https://siderite.dev/blog/careful-when-reusing-javascript-regexp.html
"The moral of the story is to be careful of constructs like _reg.test(input);
when _reg is a global regular expression. It will attempt to match from the index of the last match in any previous string."
So the problem comes from the way the global statement is treated.
The author of the blog also describes the very same problem you have:
"Here is a case that was totally weird. Imagine a javascript function that returns an array of strings based on a regular expression match inside a for loop. In FireFox it would return half the number of items that it should have."
What you could do to avoid this problem is either not using the global keyword, or instanciate a new regex at each iteration:
const txtArr = ['Year-2019-low-level', 'Year-2019-high-level', 'Year-low-level', 'Year-high-level', 'Year-2018-low-level', 'Year-2018-low-level']
for (const s of txtArr) {
console.log(/Year-\d{4}-\b(low|high)\b-level/gi.test(s), s);
}
An alternative is to use !!s.match(template) instead of template.test(s), so you don't need to modify your regex.
Working example: https://codesandbox.io/s/zen-carson-z9cq6
An explanation to the weird behavior:
The RegExp object keeps track of the lastIndex where a match occurred,
so on subsequent matches it will start from the last used index,
instead of 0.
from this StackOverflow question: Why does a RegExp with global flag give wrong results?
I changed your regex and its working, with this one:
const template = /Year-\d{4}-(low|high)-level/

How do I insert something at a specific character with Regex in Javascript [duplicate]

This question already has answers here:
Simple javascript find and replace
(6 answers)
Closed 5 years ago.
I have string "foo?bar" and I want to insert "baz" at the ?. This ? may not always be at the 3 index, so I always want to insert something string at this ? char to get "foo?bazbar"
The String.protype.replace method is perfect for this.
Example
let result = "foo?bar".replace(/\?/, '?baz');
alert(result);
I have used a RegEx in this example as requested, although you could do it without RegEx too.
Additional notes.
If you expect the string "foo?bar?boo" to result in "foo?bazbar?boo" the above code works as-is
If you expect the string "foo?bar?boo" to result in "foo?bazbar?bazboo" you can change the call to .replace(/\?/g, '?baz')
You don't need a regular expression, since you're not matching a pattern, just ordinary string replacement.
string = 'foo?bar';
newString = string.replace('?', '?baz');
console.log(newString);

Regular Expression only returning first result found [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I match multiple occurrences with a regex in JavaScript similar to PHP’s preg_match_all()?
I am trying to parse an xml document like this:
var str = data.match("<string>" + "(.*?)" + "</string>");
console.log(str);
I want to get all the elements between the [string] in an array but for some reason, it only returns the first string element found. Im not good with regular expressions so Im thinking this is just a small regex issue.
You want it to be global g
var str="<string>1</string><string>2</string><string>3</string>";
var n=str.match(/<string>(.*?)<\/string>/g);
//1,2,3
You have to form the RegEx adding a g to it like
/Regex/g

javascript - How to do replaceAll? [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
Hi I have a problem here. I am trying to replace all instances of + character in a string using javascript. What happens is that only the first instance is being changed.
Here is my code:
var keyword = "Hello+Word%+";
keyword = keyword.replace("+", encodeURIComponent("+"));
alert(keyword);
The output is Hello%2BWord%+ when it should be Hello%2BWord%%2B because there are 2 instances of +.
You can check this on : http://jsfiddle.net/Wy48Z/
Please help. Thanks in advance.
You need the global flag.
Fixed for you at http://jsfiddle.net/rtoal/Wy48Z/1/
var keyword = "Hello+Word%+";
keyword = keyword.replace(/\+/g, encodeURIComponent("+"));
alert(keyword);​
The javascript regex, which is done by putting the expresison inbetween two forward slashes like: /<expression/
If you want to replace all, simply append a g after the last one like:
/<expression/g
In your case, it would be /\+/g
The cross-browser approach is to use a regexp with the g (global) flag, which means "process all matches of the pattern, not just the first":
keyword = keyword.replace(/\+/g, encodeURIComponent("+"));
Notice I prefix the plus sign with a backslash because it would otherwise have the special meaning of "match one or more of the preceding thing".

Categories

Resources