Regex producing wrong results in google script - javascript

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

Related

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

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

Javascript extract only the capturing group

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

how to get numbers from a string in javascript?

I have
"id": 1468306
inside of a string, how can I use regular expression to get the number 1468306 for it?
You can use this regex:
/: (\d+)/
as in:
s = '"id": 1468306';
r = /: (\d+)/;
console.log(r.exec(s)[1]);
Output:
1468306
you can use parseInt() method in javascript as follows:
var str = parseInt(id);
Following code may help you:
var input = '"id": 1468306';
var matches = input.match(/"id": (\d+)/);
var id = matches[1];
The id get the required number.
JSON.parse("{" + yourString + "}").id
Will be your number if you have that in a String.
Fiddle: http://jsfiddle.net/SfeMh/
var regEx = /\d+/g;
var str = '"id": 1468306';
var numbers = str.match(regEx);
alert(numbers); // returns 1468306
It looks like you're trying to parse a JSON String. Try this way as already mentioned:
var parsedObj = JSON.parse(myJSONString);
alert(parsedObj.id); // returns 1468306
This will match in this cases
id : 156454;
id :156454;
id:156454;
/id\s?[:]\s?[0-9]+/g.match(stringhere)
Alright, my JSON answer still stands, use it if that's your full string you're giving us in the question. But if you really want a regex, here's one that will search for "id" and then find the number after.
parseInt(yourString.match(/("id"\s?:\s?)(\d+)/)[2])
Fiddle: http://jsfiddle.net/tS9M4/

Javascript string.match refuses to return an array of more than one match

I have a string that I expect to be formatted like so:
{List:[Names:a,b,c][Ages:1,2,3]}
My query looks like this in javascript:
var str = "{List:[Names:a,b,c][Ages:1,2,3]}";
var result = str.match(/^\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}$/g);
Note: I recognize that with this regex it would pass with something like "Ages:,,,", but I'm not worried about that at the moment.
I was expecting to get this back:
result[0] = "{List:[Names:a,b,c][Ages:1,2,3]}"
result[1] = "a,b,c"
result[2] = "1,2,3"
But no matter what I seem to do to the regular expression, it refuses to return an array of more than one match, I just get the full string back (because it passes, which is a start):
result = ["{List:[Names:a,b,c][Ages:1,2,3]}"]
I've looked through a bunch of questions on here already, as well as other 'intro' articles, and none of them seem to address something this basic. I'm sure it's something foolish that I've overlooked, but I truly have no idea what it is :(
So this is a difference in how the global flag is applied in Regular Expressions in JavaScript.
In .match, the global flag (/g at the end) will return an array of every incident where the regular expression matches the string. Without that flag, .match will return an array of all of the groupings in the string.
eg:
var str = "{List:[Names:a,b,c][Ages:1,2,3]}";
str += str;
// removed ^ and $ for demonstration purposes
var results = str.match(/\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}/g)
console.log(results)
// ["{List:[Names:a,b,c][Ages:1,2,3]}", "{List:[Names:a,b,c][Ages:1,2,3]}"]
str = "{List:[Names:a,b,c][Ages:1,2,3]}{List:[Names:a,b,c][Ages:3,4,5]}";
results = str.match(/\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}/g);
console.log(results)
//["{List:[Names:a,b,c][Ages:1,2,3]}", "{List:[Names:a,b,c][Ages:3,4,5]}"]
Now, if we remove that /g flag:
// leaving str as above
results = str.match(/\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}/);
console.log(results)
//["{List:[Names:a,b,c][Ages:1,2,3]}", "a,b,c", "1,2,3"]
And as a note as to why regex.exec worked, that is because:
If the regular expression does not include the g flag, returns the same result as regexp.exec(string).
You're looking for the form needle.exec(haystack)
From my console:
> haystack = "{List:[Names:a,b,c][Ages:1,2,3]}";
"{List:[Names:a,b,c][Ages:1,2,3]}"
> needle = /^\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}$/g ;
/^\{List:\[Names:([a-zA-z,]*)\]\[Ages:([0-9,]*)\]\}$/g
> needle.exec(haystack);
["{List:[Names:a,b,c][Ages:1,2,3]}", "a,b,c", "1,2,3"]

Categories