Simple way to change current URL - javascript

I am trying to find a simpler way to change 2 variables on the current url without having to split the url and re-building it.
for example if i have a url http://www.anysite.com/any/12/this/url/10/20 and want to change the last to variables 10 and 20 to 20 and 30 for example is there are simpler way than using window.location.href.split("/") then having to re-build the whole url?

With the regexp function replace:
url.replace(/([0-9]*)\/([0-9]*)$/, function( str , n1 , n2 ){
var new_n1 = 10 + parseInt( n1 , 10 );
var new_n2 = 10 + parseInt( n2 , 10 );
return new_n1 + '/' + new_n2;
});
this replaces a part of the string which have the format: [number]/[number] and which is at the end of the string 'url' (because there's a $ at the end of the pattern) by a string which have the format: [number+10]/[number+10].

Using a regular expression would be the best way to avoid spilting, if that's what you want.
See (for instance):
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp
As for replacing the URL, it would be a matter of location.replace(/* new URL here*/), with the benefit of actually replacing the URL in the browser history.

You can grab it is a string then trim and append as you see fit.
You could grab it as a string and use search and replace.
You could grab it as a string and run GREP against it.
But, honestly, might be easiest to just do the split/array thing.
It all depends on the formatting rules you have to adhere to.

You can use a regex:
var url = "http://www.anysite.com/any/12/this/url/10/20";
var newURL = url.replace(/10\/20$/, "20/30");
This regex looks for "10/20" at the end of the URL and replaces it with "20/30". Depending upon what exact circumstances you want to do the replacement, you might tweak the regex a bit to allow or disallow certain situations.

Ok, here is a function you can use.
function amendHref( a, b) {
var str = window.location.href;
var newHref = str.replace( /[\d]+\/[\d]+$/, a + "/" + b );
// ^^^^^ digit one or more times
// ^^ ( escaped ) forward slash
// ^^^^ digit one or more times
// ^ end of string
window.location.href = newHref;
}
Fiddle here

Related

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

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

Changing character between two strings

How can i change the character after "#overlay/" and before "/" after that first one?
var x = "www.foo.com/#overlay/2/";
x.replace(/#overlay\/([^]*)\//, "1"); // i'm expecting: www.foo.com/#overlay/1/
I'm using this code, but no success. I don't understand that much from regex.
I've searched some questions but without success.
I would not use a regular expression here. You can just use .split().
var url, newUrl, peices;
url = 'www.foo.com/#overlay/2/';
// Split the string apart by /
peices = url.split('/');
// Changing the 3 element in the array to 1, it was originally 2.
peices[2] = 1;
// Let's put it back together...
newUrl = peices.join('/');
You're making 3 mistakes :
you're replacing too much
you don't use the returned value. replace doesn't change the passed string (strings are immutable) but returns a new one
you forgot to precise in your capturing group when to stop (in fact it doesn't even have to be a capturing group)
You can do this :
x = x.replace(/(#overlay\/)[^\/]*\//, "$11/");
$1 here refers to the first captured group, so that you don't have to type it in the replacement string.
For example it changes
"www.foo.com/#overlay/2/rw/we/2345"
into
"www.foo.com/#overlay/1/rw/we/2345"

Regular expression in Javascript (without jQuery)?

I am new to Javascript and recently I wanted to use regular expression in order to get a number from url and store it into a var as string and another var as digit. For example I want to get the number 55 from the below webpage (which is not an accrual page) and I want to store it in a var.
I tried this but it is not working
https://www.google.com/55.html
url.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
Please I need help but not with jQuery because it does not make a lot of sense to me.
var numPortion = url.match(/(\d+)\.html/)[1]
(Assumes a match; if it might not match, check the results before applying the array subscript.)
Try this
var a="https://www.google.com/55.html";
var match = a.match(/(\d+)(\.html)/);
match is an array,
match[0] contains the matched expression from your script,
match[1] is the number (the 1st parenthesis),
and so on
var url = 'http://www.google.com/55.html';
var yournumber = /(\d+)(\.html)$/.exec(url);
yournumber = yournumber && yournumber[1]; // <-- shortcut for using if else

Simple Regex question

I want to remove this from a url string
http://.....?page=1
I know this doesn't work, but I was wondering how you would do this properly.
document.URL.replace("?page=[0-9]", "")
Thanks
It seems like you want to get rid of the protocol and the querystring. So how about just concatenating the remaining parts?
var loc = window.location;
var str = loc.host + loc.pathname + loc.hash;
http://jsfiddle.net/9Ng3Z/
I'm not entirely certain what the requirements are, but this fairly simple regex works.
loc.replace(/https?\:\/\/([^?]+)(\?|$)/,'$1');
It may be a naive implementation, but give it a try and see if it fits your need.
http://jsfiddle.net/9Ng3Z/1/
? is a regex special character. You need to escape it for a literal ?. Also use regular expression literals.
document.URL.replace(/\?page=[0-9]/, "")
The answer from #patrick dw is most practical but if you're really curious about a regular expression solution then here is what I would do:
var trimUrl = function(s) {
var r=/^http:\/\/(.*?)\?page=\d+.*$/, m=(""+s).match(r);
return (m) ? m[1] : s;
}
trimUrl('http://foo.com/?page=123'); // => "foo.com/"
trimUrl('http://foo.com:8080/bar/?page=123'); // => "foo.com:8080/bar/"
trimUrl('foobar'); // => "foobar"
You're super close. To grab the URL use location.href and make sure to escape the question mark.
var URL = location.href.replace("\?page=[0-9]", "");
location.href = URL; // and redirect if that's what you intend to do
You can also strip all query string parameters:
var URL = location.href.replace("\?.*", "");

Categories

Resources