Javascript string.replace with regex - javascript

I want to replace a url querystring parameter with a new value if it already exists or add it on if not.
e.g.
The current url could be:
a. www.mysite.com/whatever.asp?page=5&version=1 OR
b. www.mysite.com/whatever.asp?version=1
I need the resulting url to be www.mysite.com/whatever.asp?page=1&version=1
I suspect I can use string.replace with a regex to do this the most intelligent way but am hoping for a little help with it from someone more experienced with regexs :) Thanks!

I would rather use location.search along with some .splits() and Array.prototype.somehelp.
var s = location.search.slice(1).split(/&/);
check = s.some(function(elem) {
return elem.split(/=/)[0] === 'page';
});
if(!check) s.push('page=1');
location.href = location.hostname + location.pathname + '?' + s.join('&');

I think the clearest solution would be to write one regex that parses the URL, and then build a URL from there. Here's what I would do:
function urlCleanup(url) {
var match = /http:\/\/www\.mysite\.com\/whatever.asp\?(page=(\d+))?&?(version=(\d+))?/.exec(url);
var page = match[2] ? match[2] : "0";
var version = match[4] ? match[4] : "0";
return "http://www.mysite.com/whatever.asp?page=" + page + "&version=" + version;
}
var testUrls = [ "http://www.mysite.com/whatever.asp?page=4"
, "http://www.mysite.com/whatever.asp?version=5"
, "http://www.mysite.com/whatever.asp?page=4&version=5" ];
for(i in testUrls)
console.log(urlCleanup(testUrls[i]));
One problem this doesn't handle is having the variables in the opposite order in the url (e.g. ?version=5&page=2). To handle that, it would probably make more sense to use two regexes to search the URL for each parameter, like this:
function urlCleanup(url) {
var match, page, version;
match = /version=(\d+)/.exec(url);
version = match ? match[1] : "0";
match = /page=(\d+)/.exec(url);
page = match ? match[1] : "0";
return "http://www.mysite.com/whatever.asp?page=" + page + "&version=" + version;
}
var testUrls = [ "http://www.mysite.com/whatever.asp?page=4"
, "http://www.mysite.com/whatever.asp?version=5"
, "http://www.mysite.com/whatever.asp?version=5&page=2"
, "http://www.mysite.com/whatever.asp?page=4&version=5" ];
for(i in testUrls)
console.log(urlCleanup(testUrls[i]));

Related

add to URL after last /

using jQuery; to add something to a url after the last /
for example add sale to:
/gender/category/brand/
so it becomes:
/gender/category/brand/sale
However due to the way the URL's are generated and built I can't just always say 'add it to the end of a URL' as there are sometimes ?query strings on the end for example:
/gender/category/brand/?collection=short&colour=red
I just can't figure out how I can add sale after the final / and always before a ?query string if one exists.
Searching through stackoverflow I've seen some bits about extracting content after the last / but not this, is this possible? I really would appreciate help getting this sorted.
EDIT - The solution
Thanks too all for your help but I was able to adapt Shree's answer the easiest to get this which did what I needed:
if(window.location.href.indexOf("sale") > -1) {
} else {
var raw = window.location.href;
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
window.location.href = newUrl;
}
Use substring with lastIndexOf.
var raw = '/gender/category/brand/?collection=short&colour=red';
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
console.log(newUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In vanilla javascript
var a = "/gender/category/brand/?collection=short&colour=red";
var lastIndexPosition = a.lastIndexOf('/');
a = a.substring(0,lastIndexPosition+1)
+"sale"
+a.substring(lastIndexPosition+1 , a.length);
console.log(a);
By using a reusable function in Javascript:
You can use lastIndexOf and get the last '/' index position and append your new data there.
The lastIndexOf() method returns the position of the last occurrence
of a specified value in a string.
Using this you can send any parameter into function there by it is reusable.
function insert(main_string, ins_string, pos) {
return main_string.slice(0, pos) + ins_string + main_string.slice(pos);
}
var url = "/gender/category/brand/?collection=short&colour=red"
url = insert(url, 'sale', url.lastIndexOf("/") + 1)
console.log(url)
Here is a working DEMO
An alternative, use .split("?") to separate at the ? then combine them back, eg:
// Example with querystring
var url = '/gender/category/brand/?collection=short&colour=red'
var parts = url.split("?");
var newurl = parts[0] + "sale" + "?" + (parts[1]||"")
console.log(newurl)
// Test without querystring
var url = '/gender/category/brand/'
var parts = url.split("?");
var newurl = parts[0] + "sale" + (parts[1]||"")
console.log(newurl)
The (parts[1]||"") handles the case where there isn't a querystring.

Removing Url and Include Id using Regex and Jquery

I am new to Regex and my question is how can i include the ID from the url and remove it using Regex? because as of now , It only removes the actionMe=reload&Id= but the Id still return so after removing it and replacing with new Url, the old id is still included plus the new ID,
Example, Before removing and replacing the Url:
http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=15
And After Removing and replacing the url , it goes like this:
http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=1615
This is my Code Snippet:
var sss = $("#Id").val();
if (window.location.href.indexOf("&actionMe=reload&Id=") > -1) {
var regex = /(\&|&)actionMe=reload&Id=/;
var location = window.location.href;
if (regex.test(location)) {
window.location = location.replace(regex, "&actionMe=reload&Id=" + sss)
}
}
Thanks for Answering guys:)
you can use this code to update url parameters
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
I got it here
Now, in your case, you can use it like this
var url = window.location.href;
var sss = $("#Id").val();
var newUrl = updateQueryStringParameter(url, "id", sss);
//do whatever you want to newUrl
//to redirect to new url
window.location = newUrl;
Pretty sure all you need is /&Id=\d+/ as your RegExp. Don't need to select any of actionMe=reload unless you need that for specification (in that case, just add it back). The rest of your code works as intended, just your regex not selecting the precise part you were wanting.
Explanation:
The (\&|&) part of your regex is redundant, as & does not need to be escaped to work. As a matter of fact, since it's in parenthesis, you would end up capturing that & character, if you REALLY need that part, try (?:\&|&) to ignore the capture group. Your code replaced the matched regex, but did not include the number "15" after Id=, which is why it appended 15 after your edited version due to it not being matched and therefore not being replaced. Adding \d+ will select any trailing digits. This should give you the result you wanted.

Remove sections of url to only keep file name

I want to remove everything in the URL and only keep the name of the file/image. The URL is a dynamic input/variable.
Code:
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str = str.replace("http://website.com/sudir/sudir/subdir/", "")
.replace(/[^a-z\s]/gi, ' ').replace("_", " ")
.replace("subdir", "").toLowerCase().slice(0,-4);
You can do this easily with lastIndexOf():
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
str.substring(str.lastIndexOf("/") + 1)
//"Image_01.jpg"
This function will give you the file name,
function GetFilename(url)
{
if (url)
{
var m = url.toString().match(/.*\/(.+?)\./);
if (m && m.length > 1)
{
return m[1];
}
}
return "";
}
From How to catch the end filename only from a path with javascript?
var filename = path.replace(/.*\//, '');
From Getting just the filename from a path with Javascript
var fileNameIndex = yourstring.lastIndexOf("/") + 1;
var filename = yourstring.substr(fileNameIndex);
I know you haven't specified the exact URL format and whether this may be possible in your situation, but this may be a solution worth considering.
Javascript
var str = "http://website.com/sudir/sudir/subdir/Image_01.jpg?x=y#abc";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);
str = "http://website.com/sudir/sudir/subdir/Image_01.jpg";
console.log(str.split(/[?#]/)[0].split("/").slice(-1)[0]);
On jsfiddle
You can always Regex to extract data from strings:
The Regex to extract data from URL:
"http://website.com/sudir/sudir/subdir/(?<FileName>[0-9A-Za-z._]+)"

Regex for parsing parameters from url

I'm a total noob with regexes and although I was trying hard I cannot create proper regexes to perform the following operation :
take url and check if it has a '?' followed by number with varying amount of digits.
if the match is correct, get the number after the '?' sign
exchange this number with different one.
So let's say we have this url :
http://website.com/avatars/avatar.png?56
we take '56' and change it to '57'.
I have the following regex for searching, I'm not sure if it's proper :
\?[0-9]+
But I have no idea how to take ? away. Should I just throw it away from the string and forget about using regex here ? Then the replace part is the only one left.
Try this:
var url = "http://website.com/avatars/avatar.png?56";
var match = url.match(/\?(\d+)/);
if(match != null) {
url = url.replace(match[1], "new number");
}
Your original regex will work just fine, just add back in the ? you are taking out like so:
var newnum = 57;
url = url.replace(/\?[0-9]+/, '?'+ newnum);
I'm no regex expert but I think you can use a lookaround to ignore the '?'
(?<=?)([0-9]+)
which should give you your number in the first match
VERY dummied-down approach:
$('#parse').click(function(e){
var fromUrl = $('#from-url').val();
var newNum = parseInt($('#new-number').val(), 10);
var urlRE = /(?!\?)(\d+)$/;
if (urlRE.test(fromUrl)){
$('#result').text(fromUrl.replace(urlRE, newNum));
}else{
$('#result').text('Invalid URL');
}
});
DEMO
There are not extravagant check-sums, error-checking, etc. Fromt here, use window.location or a string containing the URL if necessary.
Broken out in to a function (demo):
// Call this to replace the last digits with a new number within a url.
function replaceNumber(url, newNumber){
// regex to find (and replace) the numbers at the end.
var urlRE = /\?\d+$/;
// make sure the url end in a question mark (?) and
// any number of digits
if (urlRE.test(url)){
// replace the ?<number> with ?<newNumber>
return url.replace(urlRE, '?'+newNumber);
}
// invalid URL (per regex) just return same result
return url;
}
alert(replaceNumber('http://website.com/avatars/avatar.png?56', 57));
You could do this without regex.
var newNum = "57";
var url = "http://website.com/avatars/avatar.png?56";
var sUrl = url.split('?');
var rUrl = sUrl[0] + "?" + newNum;
alert(rUrl);
Split the URL at the ?
This returns an array.
Add the first item in the array and the ? and the new number back together.
http://jsfiddle.net/jasongennaro/7dMur/

How to grab the last bit of a url before the "?" in JavaScript?

I'm using this to grab the last part of the url:
url = window.location.href;
parts = url.split("/");
if (parts[parts.length-1].length == 0) {
lastBit = parts[parts.length-2];
} else {
lastBit = parts[parts.length-1];
}
The above works with or without a forward slash. So if my url was:
http://mysite.com/path/to/welcome/
I would get just this:
welcome
But what if my url is:
http://mysite.com/path/to/welcome/?foo=bar&hello=bye
How can I still get "welcome" and disregard everything that comes after it?
How about
var urlWithoutSearch = location.href.replace(location.search, '');
Just use location.pathname:
var parts = window.location.pathname.replace(/\/$/, '').split('/'),
lastBit = parts[parts.length - 1];
The replace() gets rid of a trailing / character, if present. (We don't care about a leading / in this case.)
Ex.
> '/path/to/welcome/'.replace(/\/$/, '').split('/')
> ["", "path", "to", "welcome"]
Look at window.location.pathname and work with this. This variable just includes the path and does not include any query parameters. So in your example you would be left with /path/to/welcome and parsing that is trivial.
lastBit = window.location.pathname.match(/\/([^\/]+?)\/(?:\?|$)/i)[1];
Do a split on ? before.
url = window.location.href;
urlParts = url.split('?');
parts = urlParts[0].split("/");
if (parts[parts.length-1].length == 0) {
lastBit = parts[parts.length-2];
} else {
lastBit = parts[parts.length-1];
}
First remove the query-string by:
url = window.location.href.replace(window.location.search, "");

Categories

Resources