Javascript extract only the capturing group - javascript

I need to extract an id from a string but I can't only the ID. I'm trying to user a pattern that works fine in Java, but in JS it yields more results than I like. Here is my code:
var reg = new RegExp("&topic=([0-9]+)");
When applying execute this against the string "#p=activity-feed&topic=1697"
var results = reg.exec("#p=activity-feed&topic=1697");
I was hoping to get just the number part (1697, in this case) because this was preceded by "&topic=", but this is returning two matches:
0: "&topic=1697"
1: "1697"
Can someone help me to get ["1967","9999"] from the string "#p=activity-feed&topic=1697&no_match=1111&topic=9999"?

Assuming the browser support is right for your use case, URLSearchParams can do all of the parsing for you:
var params = new URLSearchParams('p=activity-feed&topic=1697&no_match=1111&topic=9999');
console.log(params.getAll('topic'));

While Noah's answer is arguably more robust and flexible, here's a regex-based solution:
var topicRegex = /&topic=(\d+)/g; // note the g flag
var results = [];
var testString = "p=activity-feed&topic=1697&no_match=1111&topic=9999";
var match;
while (match = reg.exec(testString)) {
results.push(match[1]); // indexing at 1 pulls capture result
}
console.log(results); // ["1697", "9999"]
Works for any arbitrary number of matches or position(s) in the string. Note that the matches are still strings, if you want to treat them as numbers you'll have to do something like:
var numberized = results.map(Number);

Related

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

How to rewrite this RegExp to not use deprecated API?

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

Regex producing wrong results in google script

I am trying to use regex to extract something from a string. I know I don't have to use the global operator as I only need one match but I am curious why it isn't working
var string = 'a02_ability10'
string.match(/(?:^a)([\d]+)/gi)
this doesn't give me any results. remove the global operator it works. I have used it with the global operator in regex tester and it works.
Trying to get "02" out
Why isn't it working here?
Without gi, it gives the full matched string and group matched string ([\d] i.e., 12) at next position.(return Only first matched string )
var string = 'a12_ability10'
string.match(/(?:^a)([\d]+)/)
Result : ["a12", "12", index: 0, input: "a12_ability10"]
With gi :it will give only full matched string.
Result : ["a12"]
Please find below example for better understanding.
var string = 'a12_ability10'
var result =string.match(/(?:^a)([\d]+)/)
console.log(result);
var string = 'a12_ability10'
var result =string.match(/(?:^a)([\d]+)/gi)
console.log(result);
var string = 'a12_a10'
var result= string.match(/(?:a)([\d]+)/);
console.log(result);
var result= string.match(/(?:a)([\d]+)/gi);
console.log(result);

Using RegExp to substring a string at the position of a special character

Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);

get all but last occurrences of a pattern in javascript

Given the following patterns:
"profile[foreclosure_defenses_attributes][0][some_text]"
"something[something_else_attributes][0][hello_attributes][0][other_stuff]"
I am able to extract the last part using non-capturing groups:
var regex = /(?:\w+(\[\w+\]\[\d+\])+)(\[\w+\])/;
str = "profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]";
match = regex.exec(str);
["profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]", "[properties_attributes][0]", "[other_stuff]"]
However, I want to be able to get everything but the last part. In other words, everything but [some_text] or [other_stuff].
I cannot figure out how to do this with noncapturing groups. How else can I achieve this?
Something like?
shorter, and matches from the back if you can have more of the [] items.
var regex = /(.*)(?:\[\w+\])$/;
var a = "something[something_else_attributes][0][hello_attributes][0][other_stuff11][other_stuff22][other_stuff33][other_stuff44]".match(regex)[1];
a;
or using replace, though less performant.
var regex = /(.*)(?:\[\w+\])$/;
var a = "something[something_else_attributes][0][hello_attributes][0][other_stuff11][other_stuff22][other_stuff33][other_stuff44]".replace(regex, function(_,$1){ return $1});
a;
If those really are your strings:
var regex = /(.*)\[/;

Categories