Regular Expression wrong match - javascript

I am trying a regex to validate an Url.
var url = "https://www,google.com";
var urlRegex = /(https|http)?:\/\/(?:\w[\-\w.]+)(?:\/[\-\w+&##\/%=~_|!:,.;]*)?(?:\?[\-A-Z0-9+&##\/%=~_|!:,.;]*)?/i;
var result = urlRegex.test(url);
so i am getting "result" as true but i should get false as "url" contains comma.
Kindly help.

Add anchors (^ for beginning of a string, and $ for the end of the string):
^(https|http)?:\/\/(?:\w[\-\w.]+)(?:\/[\-\w+&##\/%=~_|!:,.;]*)?(?:\?[\-A-Z0-9+&##\/%=~_|!:,.;]*)?$
^ ^
See demo

You are getting true since your regex partly matches.
Use ^(https|http)?:\/\/(?:\w[\-\w.]+)(?:\/[\-\w+&##\/%=~_|!:,.;]*)?(?:\?[\-A-Z0-9+&##\/%=~_|!:,.;]*)?$
instead.

Related

remove last part of string following '&&&' with JavaScript Regex

I'm trying to use a regex in JS to remove the last part of a string. This substring starts with &&&, is followed by something not &&&, and ends with .pdf.
So, for example, the final regex should take a string like:
parent&&&child&&&grandchild.pdf
and match
parent&&&child
I'm not that great with regex's, so my best effort has been something like:
.*?(?:&&&.*\.pdf)
Which matches the whole string. Can anyone help me out?
You may use this greedy regex either in replace or in match:
var s = 'parent&&&child&&&grandchild.pdf';
// using replace
var r = s.replace(/(.*)&&&.*\.pdf$/, '$1');
console.log(r);
//=> parent&&&child
// using match
var m = s.match(/(.*)&&&.*\.pdf$/)
if (m) {
console.log(m[1]);
//=> parent&&&child
}
By using greedy pattern .* before &&& we make sure to match **last instance of &&& in input.
You want to remove the last portion, so replace it
var str = "parent&&&child&&&grandchild.pdf"
var result = str.replace(/&&&[^&]+\.pdf$/, '')
console.log(result)

How to use specific website in regex

I want the regex pattern to only match a9.com or www.a9.com
I have tried add ? before www. /?([www]+\.)+[\ba9\.com\b]/; but it shows error..
Did I miss anything ?
hope this result
a9.com true
www.a9.com true
a91.com false
www.a91.com false
https://jsfiddle.net/c2wsds0g/
var str = 'a9.com';
var regexPattern = /([www]+\.)+[\ba9\.com\b]/;
var result = regexPattern.test(str);
console.log(result)
only regex. not use split or other method
This Regex sould do the trick:
(www\.)?a9\.com
The ´?´ quantifier, to make the group optional goes after the group, not before.
Bonus: I always test my regex with regexpal.com, you should try it. You´ll find a handy cheat sheet there too.

Getting cannot read property '0' of null in a regex

I want to get the filename from an url. I'm doing this:
console.log(url)
const filename = url.match(/([^\/]+)(?=\.\w+$)/)[0]
return filename
But I get TypeError: Cannot read property '0' of null. Which is strange, because console.log(url) outputs the file: http://ac-0uhksb6K.clouddn.com/9710016c8dfcf6ae1e9d.jpg?imageView2/2/w/4096/h/2048/q/100/format/jpg
What could be the problem?
Your regex expects the filename with its extension to be the last part of a URL, while the URL in the question has also query parameters. In order to take these into account add the (?:$|\?) alternation to the lookahead:
[^\/]+(?=\.\w+(?:$|\?))
Note: the capture group is redundant so removed it as well.
Demo: https://regex101.com/r/nX2rP5/3
If there are no matches, then there is no array on which to select the first item with [0].
You'll want to check the array has at least one item first...
The error occurs because there is no match, see your regex demo. The issue is that the lookahead (?=\.\w+$) requires the .+1 or more word chars before the end of string $. You need to allow checking the ? query string start marker, too.
NOTE that you actually do not have to use lookarounds at all. Use a capturing group - ([^\/]+)\.\w+(?:\?|$) and access [1] item.
See the regex demo
Also, it is always a good idea to check if a match occurred at all before accessing capture groups.
var re = /([^\/]+)\.\w+(?:\?|$)/;
var str = 'file: http://ac-0uhksb6K.clouddn.com/9710016c8dfcf6ae1e9d.jpg?imageView2/2/w/4096/h/2048/q/100/format/jpg';
var match = str.match(re);
if (match) {
console.log(match[1]);
}

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

How to find in javascript with regular expression string from url?

Good evening, How can I find in javascript with regular expression string from url address for example i have url: http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/ and I need only string between last slashes (/ /) http://something.cz/something/string/ in this example word that i need is mikronebulizer. Thank you very much for you help.
You could use a regex match with a group.
Use this:
/([\w\-]+)\/$/.exec("http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/")[1];
Here's a jsfiddle showing it in action
This part: ([\w\-]+)
Means at least 1 or more of the set of alphanumeric, underscore and hyphen and use it as the first match group.
Followed by a /
And then finally the: $
Which means the line should end with this
The .exec() returns an array where the first value is the full match (IE: "mikronebulizer/") and then each match group after that.
So .exec()[1] returns your value: mikronebulizer
Simply:
url.match(/([^\/]*)\/$/);
Should do it.
If you want to match (optionally) without a trailing slash, use:
url.match(/([^\/]*)\/?$/);
See it in action here: http://regex101.com/r/cL3qG3
If you have the url provided, then you can do it this way:
var url = 'http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/';
var urlsplit = url.split('/');
var urlEnd = urlsplit[urlsplit.length- (urlsplit[urlsplit.length-1] == '' ? 2 : 1)];
This will match either everything after the last slash, if there's any content there, and otherwise, it will match the part between the second-last and the last slash.
Something else to consider - yes a pure RegEx approach might be easier (heck, and faster), but I wanted to include this simply to point out window.location.pathName.
function getLast(){
// Strip trailing slash if present
var path = window.location.pathname.replace(/\/$?/, '');
return path.split('/').pop();
}
Alternatively you could get using split:
var pieces = "http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/".split("/");
var lastSegment = pieces[pieces.length - 2];
// lastSegment == mikronebulizer
var url = 'http://www.odsavacky.cz/blog/wpcproduct/mikronebulizer/';
if (url.slice(-1)=="/") {
url = url.substr(0,url.length-1);
}
var lastSegment = url.split('/').pop();
document.write(lastSegment+"<br>");

Categories

Resources