remove all empty values from url string - javascript

I'm trying to remove all empty params from a url string. My url looks like this
http://localhost/wm/frontend/www/?test=&lol=1&boo=2
my code should return
http://localhost/wm/frontend/www/?lol=1&boo=2
but it doesn't instead it returns
http://localhost/wm/frontend/www/?&lol=1&boo=2
This is the regex i'm using replace("/(&?\w+=((?=$)|(?=&)))/g","") i know i could just use replace() strings that match '?&' after the 1st replace, but i would rather edit my regex to do so, so it's in 1 line of code. Any ideas?
here is my jsfiddle

You can use this regex for replacement:
/[^?&=]+=(?:&|$)|&[^?&=]+=(?=&|$)/g
And replace it by:
""
RegEx Demo

Try
/\w+=&|&\w+=$/g,
var url = "http://localhost/wm/frontend/www/?test=&lol=1&boo=2&j=";
document.write(url.replace(/\w+=&|&\w+=$/g, ""))

Just try to invoke native's 'replace', which could be used with a regex in its first argument.
str.replace(regex, replace_str)
Please, see this fiddle to see a running example: http://jsfiddle.net/xvqasgmu/1/

You can for example say:
var s = 'http://localhost/wm/frontend/www/?test=&lol=1&boo=2&r=';
s = s.replace(/\w*=\&/g, '');
s = s.replace(/&\w*=$/g, '');
That is, remove a block of letters + = + &. Then, remove & + letters + = at the end of the line (indicated by $).
For your input, it returns:
http://localhost/wm/frontend/www/?lol=1&boo=2
See it in JSFiddle or directly here:
var s = 'http://localhost/wm/frontend/www/?test=&lol=1&boo=2&r=';
s = s.replace(/\w*=\&/g, '');
s = s.replace(/&\w*=$/g, '');
document.write(s)
Test
If the input contains blocks in the middle and in the end:
http://localhost/wm/frontend/www/?test=&lol=1&boo=2&r=
the code I wrote above returns:
http://localhost/wm/frontend/www/?lol=1&boo=2

Related

How do I split a string between / and "+" based on an outgoing link click, when there are colons in the actual URL?

JS Beginner here. I need to return itemName from a URL string, however, there are colons in the URL itself. When I split using ("""), I get an error that this won't work.
I have gotten this far, but I don't know what to change in my function to get the desired result. See the examples below:
Below is the URL:
"https://www.website.com/items/item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2"
Below you can see my code.
if ({{Outgoing link}})
var itemName= {{Click URL}};
return itemName.split("/")[5].split(".")[0];
console.log(extractSliceFromUrl(itemName))
}
This is my expected result:
"item-name-1"
This is the actual result I get:
"item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2"
Would the following work?
It extracts whatever's between the last / and the first "+".
const url = "\"https://www.website.com/items/item-name-1\"+\"?date_1=2022-10-05&date_2=2022-10-07&amount=2\"";
console.log(url.substring(url.lastIndexOf('/') + 1, url.indexOf('"+"')));
I'd split by ? first:
const theURL = "https://www.website.com/items/item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2";
theURL.split("?")[0].split("/")[5].split(".")[0];
With the secondary result, you could just remove the ending using:
'"item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2"'.replace(/("[^"]+?")\+/, '$1')
Explanation of /("[^"]+?")\+/ (RegExp)
(...) catch the pattern (becomes the $1)
[^"] everything not "
+? get the shortest result possible
\+ escape + (+ is a special symbol, this will treat it as plain text)
please is the working code.
let strUrl = "https://www.website.com/items/item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2";
let urlArray = strUrl.split("/");
let itemName = urlArray[4].split("?")[0];
console.log(itemName);

regex get part of the link

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

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

Regex returns string undefined

I am trying to extract hash value from an magnet link but it returns undefined
var tesst = "magnet:?xt=urn:btih:2B78EDFDDC87DC9605FB285997A80B787888C194&"
var test = tesst.match(/magnet:\?xt=urn:btih:[a-z\d]{40}\&/im);
alert (test[1]);
I cant understand what I am doing wrong.
var test = tesst.match(/magnet:\?xt=urn:btih:([a-z\d]{40})\&/im);
You forgot the ( ) around the hash part.
just mark what you want with capturing group:
/^magnet:\?xt=urn:btih:([a-z\d]{40})\&$/im
Also I recomend to not use regexp here.
Try followed:
tesst.split(':')[3].slice(0, -1);
slice(0, -1) used for remove last '&', you can use any other method, like slice(0, 40), replace(/[^\w]/g, '') or any other.
You need to include [a-z\d]{40} part inside a capturing group and you don't need to escape & symbol, because it isn't a regex meta character.
> var test = tesst.match(/magnet:\?xt=urn:btih:([a-z\d]{40})&/im);
undefined
> console.log(test[1])
2B78EDFDDC87DC9605FB285997A80B787888C194
You can use this regex
/([^:]+)&$/
and use test[1]
console.log(str.match(/([^:]+)&$/)[1]);

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