My string is like https://www.facebook.com/connect/login_success.html?request=516359075128086&to%5B0%5D=100004408050639&to%5B1%5D=1516147434&_=_
This string is result of a app invitation url redirect request sent to fb.
And what i want to do is, to extract user ids 100004408050639 and 1516147434 to an array.
I tried var fbCode = testString.match(/to%5B0%5D=(.*)&/); but this returns only one of these numbers, ie first occurrence.
var str = "https://www.facebook.com/connect/login_success.html?request=516359075128086&to%5B0%5D=100004408050639&to%5B1%5D=1516147434&_=_";
var re = new RegExp("to%5B[01]%5D=(\\d+)", "g");
When using the g modifier for global search and want to get matches for a ( group ), could loop through the matches. Those for the first parenthesized group will be in [1]
var matches = [];
while(matches = re.exec(str)) {
console.log(matches[1]);
}
Your regex specifies %5B0%5D which translate to [0]. The second user ID comes with index 1 ([1]) which is encoded as %5B1%5D. If you want to accept any (numeric) user-Id-index, use '/to%5B\d+%5D=(.*?)&/g' as your regex which allows any number (\d+) as well as being global.
Regards.
Related
I Would like to extract the Twitter handler names from a text string, using a regex. I believe I am almost there, except for the ">" that I am including in my output. How can I change my regex to be better, and drop the ">" from my output?
Here is an example of a text string value:
"PlaymakersZA, Absa, DiepslootMTB"
The desired output would be an array consisting of the following:
PlaymakersZA, Absa, DiepslootMTB
Here is an example of my regex:
var array = str.match(/>[a-z-_]+/ig)
Thank you!
You can use match groups in your regex to indicate the part you wish to extract.
I set up this JSFiddle to demonstrate.
Basically, you surround the part of the regex that you want to extract in parenthesis: />([a-z-_]+)/ig, save it as an object, and execute .exec() as long as there are still values. Using index 1 from the resulting array, you can find the first match group's result. Index 0 is the whole regex, and next indices would be subsequent match groups, if available.
var str = "PlaymakersZA, Absa, DiepslootMTB";
var regex = />([a-z-_]+)/ig
var array = regex.exec(str);
while (array != null) {
alert(array[1]);
array = regex.exec(str);
}
You could just strip all the HTML
var str = "PlaymakersZA, Absa, DiepslootMTB";
$handlers = str.replace(/<[^>]*>|\s/g,'').split(",");
In javascript I have this code that gets an array of all matches
var m = body.match(/'(http[^,]+\/p\/[^,]+\d+)'/g);
res.write(m.join());
The problem is I need the quotes wrapped on it, to get the results I want, but when I actually get the result, I don't want the quotes included in each string in the array.
How can I remove that?
Thanks
The parentheses create a numbered capturing group, which allows you to access that part of the match.
When you use String.prototype.match, you get an array where the first element is the match, the second one is the first capturing group, and so on:
"a1a".match(/a(\d)a/); // [ "a1a", "1" ]
However, that only happens when the regex doesn't have the global g flag. Otherwise, you get an array with all matches:
"a1a-a2a".match(/a(\d)a/g); // [ "a1a", "a2a" ]
It is still possible to access the capturing groups with a global flag, but not with match:
var regex = /a(\d)a/g,
str = "a1a-a2a",
match;
while(match = regex.exec(str)) {
match[1]; // First capturing group of each match
}
I have some doubts regarding RegEx in JavaScript as I am not good in RegEx.
I have a String and I want to compare it against some array of RegEx expressions.
First I tried for one RegEx and it's not working. I want to fix that also.
function check(str){
var regEx = new RegEx("(users)\/[\w|\W]*");
var result = regEx.test(str);
if(result){
//do something
}
}
It is not working properly.
If I pass users, it doesn't match. If I pass users/ or users/somestring, it is matching.
If I change the RegEx to (usersGroupList)[/\w|\W]*, then it is matching for any string that contains the string users
fdgdsfgguserslist/data
I want to match like if string is either users or it should contain users/something or users/
And also I want the string to compare it with similar regex array.
I want to compare the string str with users, users/something, list, list/something, anothermatch, anothermatch/something. If if it matches any of these expression i want to do something.
How can I do that?
Thanks
Then, you'll have to make the last group optional. You do that by capturing the /something part in a group and following it with ? which makes the previous token, here the captured group, optional.
var regEx = new RegExp("(users)(\/[\w|\W]*)?");
What about making:
the last group optional
starting from beginning of the string
Like this:
var regEx = new RegExp("^(users)(\/[\w|\W]*)?");
Same applies for all the others cases, e.g. for list:
var regEx = new RegExp("^(list)(\/[\w|\W]*)?");
All in One Approach
var regEx = new RegExp("^(users|list|anothermatch)(\/[\w|\W]*)?");
Even More Generic
var keyw = ["users", "list", "anothermatch"];
var keyws = keyw.join("|");
var regEx = new RegExp("^("+keyws+")(\/[\w|\W]*)?");
You haven't made the / optional. Try this instead
(users)\/?[\w|\W]*
How can I use regex in javascript to match the phone number and only the phone number in the sample string below? The way I have it written below matches "PHONE=9878906756", I need it to only match "9878906756". I think this should be relatively simple, but I've tried putting negating like characters around "PHONE=" with no luck. I can get the phone number in its own group, but that doesn't help when assigning to the javascript var, which only cares what matches.
REGEX:
/PHONE=([^,]*)/g
DATA:
3={STATE=, SSN=, STREET2=, STREET1=, PHONE=9878906756,
MIDDLENAME=, FIRSTNAME=Dexter, POSTALCODE=, DATEOFBIRTH=19650802,
GENDER=0, CITY=, LASTNAME=Morgan
The way you're doing it is right, you just have to get the value of the capture group rather than the value of the whole match:
var result = str.match(/PHONE=([^,]*)/); // Or result = /PHONE=([^,]*)/.exec(str);
if (result) {
console.log(result[1]); // "9878906756"
}
In the array you get back from match, the first entry is the whole match, and then there are additional entries for each capture group.
You also don't need the g flag.
Just use dataAfterRegex.substring(6) to take out the first 6 characters (i.e.: the PHONE= part).
Try
var str = "3={STATE=, SSN=, STREET2=, STREET1=, PHONE=9878906756, MIDDLENAME=, FIRSTNAME=Dexter, POSTALCODE=, DATEOFBIRTH=19650802, GENDER=0, CITY=, LASTNAME=Morgan";
var ph = str.match(/PHONE\=\d+/)[0].slice(-10);
console.log(ph);
I'm not very used to Javascript so I'm having trouble manipulating strings...
If I have something like /folder1/folder2/folder3/ , how do I parse it so I end up with just the current folder, e.g. "folder3" ?
Thanks!
var folderName = str.match(/(folder\d+)\/$/)[1];
Should do it.
Explanation of the regex:
( -> Start of capture group. We want a capture group because we just want
the folder name without the trailing slash.
folder -> Match the string "folder"
\d+ -> Match one or more digits
) -> End of capture group. This lets us capture strings of the form
"folderN", where N is a number.
\/ -> Escape forward slash. We have to escape this because / is used to
represent the start and end of a regex literal, in Javascript.
$ -> Match the end of the string.
The reason we are selecting the second element of the array (at index 1) is because the first element contains the complete string that was matched. This is not what we want; we just want the capture group. We only have one group that we captured, and so that is the second element.
Well, just because it's an option (though not necessarily sane):
var string = '/folder1/folder2/folder3/',
last = string.replace(/\//g,' ').trim().split(/\s/).pop();
console.log(last);
JS Fiddle demo.
You can use the split function to retrieve all subpaths:
var path = '/folder1/folder2/folder3/';
var paths = path.split('/');
var pathNeeded = paths[paths.length - 2];
Working example
How stable is the format of that string?
With a trailing slash you will need the next to last item
var parts = URL.split("/"); alert(parts[parts.length-2]);
var str = "/folder1/folder2/folder3/",
folder = str.substring(0, str.length - 1).split('/').pop();
FIDDLE
The split function transform your string into an array using the supplied parameter as a delimiter.
Therefore:
var parts = "/folder1/folder2/folder3/".split("/");
Will result in parts being equal to:
["", "folder1", "folder2", "folder3", ""]
You could then access each item using:
parts[0] // returns ''
parts[1] // returns 'folder1'
parts[2] // returns 'folder2'
.. and so on. Read more on split here:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
You can write the following:
var myString = '/fold1/fold2/fold3';
var myArray = myString.split('/');
var last_element = myArray[myArray.length - 1];
See the doc split