Extracting a substring with a JavaScript regular expression; - javascript

Consider this code:
var myregexp = "\\*(.+)"; // set from another subsystem, that's why I'm not using a literal regexp
var input = "Paypal *Steam Games";
var output = input.match(new RegExp(myregexp, 'gi'), "$1");
The output is ["*Steam Games"], but I would like it to be just ["Steam Games"].
What is wrong?
PS A great resource I found today: http://regex101.com/#javascript

match doesn’t accept a second argument.
Since you have the global flag set (and I assume it’s intentional), you’ll need exec to find all of the first groups:
var m;
while ((m = re.exec(input)) {
alert(m[1]); // Get group 1
}

var str = "Paypal *Steam Games";
var reg = /\w+\s?\*(\w+\s?\w+)/; // or your exp will work too `/\*(.+)/;`
console.log(reg.exec(str)[1]); // result Steam Games
JSFiddle
You'll get Steam Games from your string with help of /\w+\s?\*(\w+\s?\w+)/ exp
In JavaScript there are three main RegExp functions:
exec A RegExp method that executes a search for a match in a
string. It returns an array of information.
match A String method that executes a search for a match in a
string. It returns an array of information or null on a mismatch.
test A RegExp method that tests for a match in a string. It
returns true or false.

Related

javascript regex match works but replace doesnt work

I am trying to use regex replace with a regex I have. When I use the match method it returns the array with the proper index and match but when I use replace and add the replace string it wouldnt work.
var a = "$#,##0.00".match("[\\d+-,#;()\\.]+");
console.log(a);
Returns ["#,##0.00", index: 1, input: "$#,##0.00"].
var b = "$#,##0.00".replace("[\\d+-,#;()\\.]+","");
console.log(b);
Returns $#,##0.00 whereas I expect it to return just the $
Can someone point out what am I doing incorrectly? Thanks
Link to the example is:
var a = "$#,##0.00".match("[\\d+-,#;()\\.]+");
console.log(a);
var b = "$#,##0.00".replace("[\\d+-,#;()\\.]+","");
console.log(b);
.match only accepts regexps. So if a string is provided .match will explicitly convert it to a regexp using new RegExp.
.replace however accepts both a string (which will be taken literally as the search) or a regexp, you have to pass in a regexp if you want it to use a regexp.
var b = "$#,##0.00".replace(new RegExp("[\\d+-,#;()\\.]+"), "");
// ^^^^^^^^^^^ ^
or using a regexp literal:
var b = "$#,##0.00".replace(/[\d+-,#;()\.]+/, "");

JavaScript String test with array of RegEx

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]*

using a lookahead to get the last occurrence of a pattern in javascript

I was able to build a regex to extract a part of a pattern:
var regex = /\w+\[(\w+)_attributes\]\[\d+\]\[own_property\]/g;
var match = regex.exec( "client_profile[foreclosure_defenses_attributes][0][own_property]" );
match[1] // "foreclosure_defenses"
However, I also have a situation where there will be a repetitive pattern like so:
"client_profile[lead_profile_attributes][foreclosure_defenses_attributes][0][own_property]"
In that case, I want to ignore [lead_profile_attributes] and just extract the portion of the last occurence as I did in the first example. In other words, I still want to match "foreclosure_defenses" in this case.
Since all patterns will be like [(\w+)_attributes], I tried to do a lookahead, but it is not working:
var regex = /\w+\[(\w+)_attributes\](?!\[(\w+)_attributes\])\[\d+\]\[own_property\]/g;
var match = regex.exec("client_profile[lead_profile_attributes][foreclosure_defenses_attributes][0][own_property]");
match // null
match returns null meaning that my regex isn't working as expected. I added the following:
\[(\w+)_attributes\](?!\[(\w+)_attributes\])
Because I want to match only the last occurrence of the following pattern:
[lead_profile_attributes][foreclosure_defenses_attributes]
I just want to grab the foreclosure_defenses, not the lead_profile.
What might I be doing wrong?
I think I got it working without positive lookahead:
regex = /(\[(\w+)_attributes\])+/
/(\[(\w+)_attributes\])+/
match = regex.exec(str);
["[a_attributes][b_attributes][c_attributes]", "[c_attributes]", "c"]
I was able to also achieve it through noncapturing groups. Output from chrome console:
var regex = /(?:\w+(\[\w+\]\[\d+\])+)(\[\w+\])/;
undefined
regex
/(?:\w+(\[\w+\]\[\d+\])+)(\[\w+\])/
str = "profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]";
"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]"]

Javascript: How to extract multiple values from a string using regex?

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.

Counting size of string with regular expression Javascript

I am having troubles getting the size of the URL i get with the regular expression. I can print the "exp" content but when i try to make an alert of exp.length it fails:
var pattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var exp = text.match(pattern);
alert(exp.length);
Any idea?
Thanks.
If, what you're trying to do is get the length of the regexp match result, you would do that like this:
var pattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var exp = text.match(pattern);
if (exp) {
alert(exp[0].length);
}
.match() returns either null (if no match was found) or an array. In that array, exp[0] would be the whole match that was found. Subsequent indexes in the array contain any subexpressions you matched (denoted with parentheses in the match string).
string.match returns an array, not a string, you are probably trying to do something like this:
var pattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var exp = text.match(pattern);
alert(exp.join('').length); // alert a string, not an array

Categories

Resources