Removing Url and Include Id using Regex and Jquery - javascript

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.

Related

Search and remove a parameter with optional character from URL

I'm looking to remove a parameter from a URL with a click event. The issue is that the parameter can either have an & before it or not. So the form is either search=MYSEARCHTERM or &search=MYSEARCHTERM.
I have the following which appears to work fine for one or other but not both. I was thinking that I could have an if / else statement one of which contains something like this. (Excuse the crappy regex but I've never written it before)
var searchKeywordRegx = new RegExp(/(?:&)/ + 'search=' + searchKeyword);
$('.searchKeyword').click(function() {
$(this).remove();
var searchKeywordRegx = new RegExp('search=' + searchKeyword);
console.log(searchKeywordRegx);
document.location.href = String( document.location.href ).replace(searchKeywordRegx , "" );
});
Am I way off base here?
Use ? to make something optional in a regexp:
var searchKeywordRegx = new RegExp('&?search=' + searchKeyword);
Seems you can do this without regular expressions. If you simply remove that portion of the document location's "search":
document.location.search = document.location.search
.replace('search=' + encodeURI(searchKeyword), '');

Replace ID in a URL between two markers

I have a url which looks like this:
I want to replace: 1034749-184e-3467-87e0-d7546df59896 with another ID, is there any regex or similar replace method which will allow me to replace the ID using JavaScript between the 'image/' and '?' characters?
You could make this approximation expression:
/[0-9a-z]+(?:-[0-9a-z]+){4}/i
Match a bunch of hexadecimals, followed by 4 sections, each starting with a dash followed by a bunch of hexadecimals.
> var s = 'http://url/images/1034749-184e-3467-87e0-d7546df59896?w=600&r=22036';
> console.log(s.replace(/[0-9a-z]+(?:-[0-9a-z]+){4}/i, 'something-else'));
http://url/images/something-else?w=600&r=22036
/images\/[^?]+/ would match, but it would replace images/ as well.
Fortunately you can pass a callback to .replace:
url.replace(/(images\/)[^?]+/, function($match, $1) {
// results in "images/<some-ID>"
return $1 + theNewId;
});
If you have a reference to the DOM element anyway, you can also just replace the last step of the path:
element.pathname =
element.pathname.substring(0, element.pathname.lastIndexOf('/') + 1) + newId;
Yes, just do this:
var url = document.getElementById("yoururlid").src;
url = url.split("/");
var newUrl = url[0] + url[1] + url[2] + url[3] + newURLID;
Why not just do this:
document.getElementById("yoururlid").src="http://url/images/" + newId + "?w=600&r=22036";

Remove last element from url

I need to remove the last part of the url from a span..
I have
<span st_url="http://localhost:8888/careers/php-web-developer-2"
st_title="PHP Web Developer 2" class="st_facebook_large" displaytext="facebook"
st_processed="yes"></span></span>
And I need to take the st_url and remove the php-web-developer-2 from it so it is just http://localhost:8888/careers/.
But I am not sure how to do that. php-web-developer-2 will not always be that but it won't have any / in it. It will always be a - separated string.
Any Help!!??
as simple as this:
var to = url.lastIndexOf('/');
to = to == -1 ? url.length : to + 1;
url = url.substring(0, to);
Here is a slightly simpler way:
url = url.slice(0, url.lastIndexOf('/'));
$('span').attr('st_url', function(i, url) {
var str = url.substr(url.lastIndexOf('/') + 1) + '$';
return url.replace( new RegExp(str), '' );
});
DEMO
Use this.
$('span').attr('st_url', function(i, url) {
var to = url.lastIndexOf('/') +1;
x = url.substring(0,to);
alert(x);
})​
You can see Demo
You could use a regular expression to parse the 'last piece of the url':
var url="http://localhost:8888/careers/php-web-developer";
var baseurl=url.replace(new RegExp("(.*/)[^/]+$"),"$1");
The RegExp thing basically says: "match anything, then a slash and then all non-slashes till the end of the string".
The replace function takes that matching part, and replaces it with the "anything, then a slash" part of the string.
RegexBuddy has a great deal of information on all this.
You can see it work here: http://jsfiddle.net/xKxLR/
var url = "http://localhost:8888/careers/php-web-developer-2";
var regex = new RegExp('/[^/]*$');
console.log(url.replace(regex, '/'));
First you need to parse the tag. Next try to extract st_url value which is your url. Then use a loop from the last character of the extracted url and omit them until you see a '/'. This is how you should extract what you want. Keep this in mind and try to write the code .

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/

Javascript string.replace with regex

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

Categories

Resources