How to rewrite this RegExp to not use deprecated API? - javascript

I have the following RegExp myRegexp, that matches numbers in a string:
var myRegexp = new RegExp('[0-9]+');
Then I have the following code that extracts numbers from a string and returns an array:
var string = '123:456';
var nums = new Array();
while(myRegexp.test(string)) {
nums.length++;
nums[nums.length - 1] = RegExp.lastMatch;
string = RegExp.rightContext;
}
Should return an array of two elements: "123", and "456".
However, RegExp.lastMatch and RegExp.rightContext are deprecated/non-standard API, and not portable. How can I rewrite this logic using portable JS API?
Thanks,

To match all numbers in a string, you'd simply use string.match(/\d/g); to match all single digits in a separate array entry, or string.match(/\d+/g); to match as numbers. There's no need for any of the things you've tried to useā€¦
let string = "2kdkane2kdkie83kdkdk303ldld";
let match = string.match(/\d+/g);
let match1 = string.match(/\d/g);
console.log('numbers:', match);
console.log('single digits:', match1);

Use the g flag to perform a global match which will find all matches without having to repeatedly test the string.
let s = '123:456'
const regexp = new RegExp(/\d+/g);
let nums = s.match(regexp);
console.log(nums);

Related

Extract substring from a string using regex in javascript

I am new to javascript, How to extract substring that matches a regex in a string in javascript?
For example in python:
version_regex = re.compile(r'(\d+)\.(\d+)\.(\d+)')
line = "[2021-05-29] Version 2.24.9"
found = version_regex.search(line)
if found:
found.group() // It will give the substring that macth with regex in this case 2.24.9
I tried these in javascript:
let re = new RegExp('^(\d+)\.(\d+)\.(\d+)$');
let x = line.match(re);
but I am not getting the version here.
Thanks in advance.
You can use RegExp.prototype.exec which returns an Array with the full match and the capturing groups matches:
const input = '[2021-05-29] Version 2.24.9';
const regex = /(\d+)\.(\d+)\.(\d+)/;
let x = regex.exec(input);
console.log(x);

How to take value using regular expressions?

I have such a string "Categ=All&Search=Jucs&Kin=LUU".How to get an array of values from this line [All,Jucs,LUU].
Here is an example
let x = /(\b\w+)$|(\b\w+)\b&/g;
let y = "Categories=All&Search=Filus";
console.log(y.match(x));
but I wanted no character &.
Since this looks like a URL query string, you can treat it as one and parse the data without needing a regex.
let query = "Categ=All&Search=Jucs&Kin=LUU",
parser = new URLSearchParams(query),
values = [];
parser.forEach(function(v, k){
values.push(v);
});
console.log(values);
Docs: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
Note: This may not work in IE, if that's something you care about.
Loop through all matches and take only the first group, ignoring the =
let x = /=([^&]+)/g;
let y = "Categories=All&Search=Filus";
let match;
while (match = x.exec(y)) {
console.log(match[1]);
}
To achieve expected result, use below option of using split and filter with index to separate Keys and values
1. Use split([^A-Za-z0-9]) to split string based on any special character other letters and numbers
2. Use Filter and index to get even or odd elements of array for keys and values
var str1 = "Categ=All&Search=Jucs&Kin=LUU";
function splitter(str, index){
return str.split(/[^A-Za-z0-9]/).filter((v,i)=>i%2=== index);
}
console.log(splitter(str1, 0)) //["Categ", "Search", "Kin"]
console.log(splitter(str1, 1))//["All", "Jucs", "LUU"]
codepen - https://codepen.io/nagasai/pen/yWMYwz?editors=1010

Get values from string through RegEx

I'm trying to get size values from a strings, which looks like:
https://example.com/eb5f16e5-9b3d-cfcd-19b0-75c6ace724e1/size/80x90/center/
I'm using match method and following RegEx:
'...'.match(/\/(\d+)x(\d+)\//g)
I hoped that the parentheses help to highlight the numbers:
But match returns only ["/80x90/"] without separate size values, like ["/80x90/", "80", "90"].
What am I'm doing wrong?
Here you can test my RegEx.
You don't need g modifier, without it you can get matching groups:
var url = 'https://example.com/eb5f16e5-9b3d-cfcd-19b0-75c6ace724e1/size/80x90/center/';
var res = url.match(/\/(\d+)x(\d+)\//);
console.log(res);
RegExp#exec will return all the captured group including the captured subexpression.
var url = 'https://example.com/eb5f16e5-9b3d-cfcd-19b0-75c6ace724e1/size/80x90/center/';
var patt = /\/(\d+)x(\d+)\//g;
var result = [];
while ((result = patt.exec(url)) !== null) {
console.log(result);
}

How can I capture word by Regex

I would like to capture the array key from a string.
Here are my words: message[0][generic][0][elements][0][default_action][url]...
I want to capture the array keys after message[0][generic][0][elements][0], and the expected results are default_action and url etc.
I have tried following patterns but not work.
message\[0\]\[generic\]\[0\]\[elements\]\[0\](?=\[(\w+)\]): it captures default_action only;
\[(\w+)\]: it captures all array keys, but includes 0, generic, elements...
Is there any regex pattern for JavaScript that make the result array inverse, like [url, default_action]?
You can replace unwanted part of a string,and then get all other keys.
var string = 'message[0][generic][0][elements][0][default_action][url][imthird]';
var regexp = /message\[0\]\[generic\]\[0\]\[elements\]\[0\]/
var answer = string.replace(regexp,'').match(/[^\[\]]+/g)
console.log(answer);
To extract any number of keys and reverse the order of the elements in resulting array:
str = "message[0][generic][0][elements][0][default_action][url]";
res = str.match(/\[([^\d\]]+)\](?=\[[^\d\]]*\]|$)/g)
.map(function(s) { return s.replace(/[\[\]]/g, "") })
.reverse();
console.log(res);
The solution using String.prototype.split() and Array.prototype.slice() functions:
var s = 'message[0][generic][0][elements][0][default_action][url]...',
result = s.split(/\]\[|[\[\]]/g).slice(-3,-1);
console.log(result);

matching values stored in variables or array with string javascript regex

Im trying to find a patterns in the sentence for regex matching.. in the code below result contains a string and we are checking if the word apple is present in it.
var patt = /apple/gi;
var newResult = patt.test(result);
I found the above code from a used case.. But i was wondering if i have more than one values and i want to check it in the string result, lets say an array with values var arr=["apple", "orange"] var patt=/arr[0]/gi will not work.. what could be the way in that scenario??
To check multiple entries, you can use the OR operator:
var patt = /apple|orange/gi;
var newResult = patt.test(result);
if you have a variable, you can do the below, IF(!) your key is regexp safe of course (that is, it doesn't contains characters which have meaning in regexp syntax):
var key = "apple";
var patt = new RegExp(key, 'gi');
var newResult = patt.test(result);
Although in this case, you might as well use indexOf:
var key = "apple";
var newResult = result.indexOf(key) > -1;
To use a string for your regex expressions, you need to create the regex using the regex constructor.
var pattern = "apple|orange";
var regex = new RegExp(pattern, "g"); // g is for global match
Read more about it here: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions

Categories