regex get part of the link - javascript

https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/
need to get "This-Part-I-Need-To-Get", with "-" symbols and capital letters at the wordstart.
All I managed to do is "/([A-Z-])\w+/g", that returns
"This" "-Part" "-I" "-Need" "-To" "-Get" "F1ST2", but I don`t need "F1ST2".
How should I do it?

It might depend on URL format, but at this point:
var url = 'https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/';
console.log(url.split('/')[4])

Try this regex
/([A-Z][a-z]|-[A-Z]|-[A-Z][a-z]-|-[A-Z]-)\w+/g
Here is a SNIPPET
var url = 'https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/';
console.log(url.match(/([A-Z][a-z]|-[A-Z]|-[A-Z][a-z]-|-[A-Z]-)\w+/g).join(''))

As #MichałSałaciński said, you should consider using split function.
BTW, if you wan't to use regular expressions, then this one will work if url format does not change : [^\/]+(?=(?:\/\w+){2}\/)
Demo
var re = /[^\/]+(?=(?:\/\w+){2}\/)/
var url = "https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/"
if(re.test(url)) {
// URL match regex pattern, we can safely get full match
var value = re.exec(url)[0];
console.log(value);
}
Explanation
[^\/]+ Any character but a slash n times
(?=...) Followed by
(?:\/\w+){2}\/ a slash and any word character (2 times) then a slash
Solution 2
This one also works using captured group 1: :\/\/[^\/]+\/[^\/]+\/([^\/]+)
Demo
var re = /:\/\/[^\/]+\/[^\/]+\/([^\/]+)/;
var url = "https://www.example.com/uk/This-Part-I-Need-To-Get/F1ST2/sometext/";
if(re.test(url)) {
// URL match regex pattern, we can safely get group 1 value
var value = re.exec(url)[1];
console.log(value );
}

Related

javascript regex to find only numbers with hyphen from a string content

In Javascript, from a string like this, I am trying to extract only the number with a hyphen. i.e. 67-64-1 and 35554-44-04. Sometimes there could be more hyphens.
The solvent 67-64-1 is not compatible with 35554-44-04
I tried different regex but not able to get it correctly. For example, this regex gets only the first value.
var msg = 'The solvent 67-64-1 is not compatible with 35554-44-04';
//var regex = /\d+\-?/;
var regex = /(?:\d*-\d*-\d*)/;
var res = msg.match(regex);
console.log(res);
You just need to add the g (global) flag to your regex to match more than once in the string. Note that you should use \d+, not \d*, so that you don't match something like '3--4'. To allow for processing numbers with more hyphens, we use a repeating -\d+ group after the first \d+:
var msg = 'The solvent 67-64-1 is not compatible with 23-35554-44-04 but is compatible with 1-23';
var regex = /\d+(?:-\d+)+/g;
var res = msg.match(regex);
console.log(res);
It gives only first because regex work for first element to test
// g give globel access to find all
var regex = /(?:\d*-\d*-\d*)/g;

Removing a query string using regex in java script

I have a requirement of removing a query parameter coming with a REST API call. Below are the sample URLs which need to be considered. In each of this URL, we need to remove 'key' parameter and its value.
/test/v1?key=keyval&param1=value1&param2=value2
/test/v1?key=keyval
/test/v1?param1=value1&key=keyval
/test/v1?param1=value1&key=keyval&param2=value2
After removing the key parameter, the final URLs should be as follows.
/test/v1?param1=value1&param2=value2
/test/v1?
/test/v1?param1=value1
/test/v1?param1=value1=&param2=value2
We used below regex expression to match and replace this query string in php. (https://regex101.com/r/pK0dX3/1)
(?<=[?&;])key=.*?($|[&;])
We couldn't use the same regex in java script. Once we use it in java script it gives some syntax errors. Can you please help us to figure out the issue with the same regex ? How can we change this regex to match and remove query parameter as mentioned above?
Obviously lookbehind isn't supported in Javascript hence your regex won't work.
In Javascript you can use this:
repl = input.replace(/(\?)key=[^&]*(?:&|$)|&key=[^&]*/gmi, '$1');
RegEx Demo
Regex is working on 2 paths using regex alternation:
If this query parameter is right after ? then we grab till & after parameter and place ? back in replacement.
If this query parameter is after & then &key=value is replaced by an empty string.
The regex works in PHP but not in Javascript because Javascript does not support lookbehind.
The easiest fix here would be to replace the lookbehind (?<=[?&;]) with the equivalent characters in a capturing group ([?&;]) and use a backreference ($1) to insert this bit back into the replacement string.
For example:
var path = '/test/v1?key=keyval&param1=value1&param2=value2';
var regex = /([?&;])key=.*?($|[&;])/;
console.log(path.replace(regex, '$1'); // outputs '/test/v1?param1=value1&param2=value2'
Not convinced regex would be the most reliable way of removing a query parameter, but that's a different story :-)
Just in case you want to do it without a regex, here is a function that will do the trick:
var removeQueryString = function (str) {
var qm = str.lastIndexOf('?');
var path = str.substr(0, qm + 1);
var querystr = str.substr(qm + 1);
var params = querystr.split('&');
var keyIndex = -1;
for (var i = 0; i < params.length; i++) {
if (params[i].indexOf("key=") === 0) {
keyIndex = i;
break;
}
}
if (keyIndex != -1) {
params.splice(keyIndex, 1);
}
var result = path + params.join('&');
return result;
};
The lookbehind feature isn't available in javascript, so to test the character before the key/value, you must match it. To make the pattern works whatever the position in the query part of the url, you can use an alternation in a non-capturing group, and you capture the question mark:
url = url.replace(/(?:&|(\?))key=[^&#]*(?:(?!\1).)?/, '$1');
Note: the # is excluded from the character class to prevent the fragment part (if any) of the url to be matched with key value.

Grab the end of a URL after the last slash with regex in javascript

I need to be able to grab the number at the end of the url, and set it as the value of a textbox. I have the following, but it's not correctly stripping out the beginning of the URL before the last slash. Instead, its doing the opposite.
<input id="imageid"></input>
var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url.com/content/assets/750";
var assetID = referrerURL.match("^(.*[\\\/])");
$("#imageid").val(assetID);
The result of the regex match should set the value of the text box to 750 in this case.
JSFiddle: Link
The simple method is to use a negated character class as
/[^\/]*$/
Regex Demo
Example
var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url.com/content/assets/750";
alert(referrerURL.match(/[^\/]*$/));
// Output
// => 750
Can use a simple split() and then pop() the resultant array
var assetID = referrerURL.split('/').pop();
Easier to read than a regex thus very clear what it is doing
DEMO
var referrerURL = "http://subdomain.xx-xxxx-x.xxx.url.com/content/assets/750";
var myregexp = /.*\/(.*?)$/;
var match = myregexp.exec(referrerURL);
$("#imageid").val(match[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="imageid"></input>
You could try avoiding the usage of regular expression for this task just by using native javascript's string functions.
Splitting the text:
var lastSlashToken = referrerURL.split("/").pop(-1);
Looking up for the last ending "/text" token:
var lastSlashToken = referrerURL.substr(referrerURL.lastIndexOf("/") + 1);
However, if you still want to use regular expression for this task, you could try using the following pattern:
.*\/([^$]+)
Working DEMO example # regex101

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

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