URL manipulation with JavaScript and regex - javascript

I am taking first steps with regular expressions. I am trying to increment the last digit in a url string but for some reason I cant figure out I increment other digits.
Example
string: http://example.com/18-something-something/6
should become: http://example.com/18-something-something/7
in practice: http://example.com/19-something-something/7
As you can see, 18 turned to 19 which is what im trying to avoid.
This is my JS:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
jQuery(document).ready(function() {
url = window.location.href;
var newrl = url.replace(/(\d+)+/g, function(match, number) {
return parseInt(number) + 1;
});
var m = url.match(/\/([^\/]+)[\/]?$/);
link = jQuery('a[class=nextpostslink]').attr('href');
if (!isNumeric(m[1])) {
jQuery('.post-content').find('img:first').wrap(jQuery("<div class='slideshow-wrapper'><a href=2>").attr("href", link));
jQuery('.post-content').find('img:first').after('<div id="start-slideshow"><img src="chevron.png"></div>');
} else {
jQuery('.post-content').find('img:first').wrap(jQuery("<div class='slideshow-wrapper'><a href=" + newrl + ">").attr("href", link));
}
});
Any idea what am I missing? thx

You don't want to have a global match (g), but removing that flag alone won't help.
If you want match with and without query parameter, then you need to make sure that it is either at the end of the string $ or right before the query parameters ? so your RegExp has to look like this:
var url = 'http://example.com/18-something-something/6?param=34';
var newrl = url.replace(/(\d+)($|\?)/, function(match, number, questionmark) {
return String(++number) + questionmark;
});
console.log(newrl);

You should use /(\d+)$/ as a regex to increment only the last digit.

I would not do this with regular expressions, truthfully.
I'd do something like:
var url = "http://example.com/18-something-something/6";
function advanceUrl(url) {
// Split the URL into chunks
var chunks = url.split("/");
// Get the last segment of the URL
var lastPage = chunks.pop();
// Increment it
lastPage++;
// And put it back
chunks.push(lastPage);
// Re-create the URL
var newUrl = chunks.join("/");
// Log it
console.log(newUrl);
// Return it.
return newUrl;
}
advanceUrl(url);

Related

Adding to a string (as numeral) with JS RegEx

Is it possible to add (+1) to a (substring) with regex/replace? For instance, if I have a string (the window location in this case) that ends in #img-{digit}, is it possible with regex to replace the digit with what it was +1?
I can match the hash like this, but I'm not sure how I can extract the number (which can be more than 2 digits! e.g. 12).
var loc = window.location,
locstr = loc.match(/#img-\d+/),
// untested:
locrep = locstr.replace(/\d/, Number($1) + 1);
Let's say that my current hash is #img-4, then I want a JS snippet that changes it to #img-5.
Use a callback in replace:
var locrep = locstr.replace(/\d+/, function($0) { return Number($0) + 1; });
//=> #img-5
Or else:
var locrep = locstr.replace(/(#img-)(\d+)/i,
function($0, $1, $2) { return $1 + (Number($2) + 1); });
//=> #img-5
Since you have the string like #img-{digit}, you can use split with - like this
var loc = window.location,
locstr = loc.split("-");
var newloc = locstr[0]+parseInt(locstr[1])+1;
Note, window.location returns window.location object ; e.g.,
console.log(typeof window.location, typeof window.location.hash);
Try
var loc = window.location.hash
, locrep = loc.match(/[^\d]/g).join("") + (1+Number(loc.match(/\d/g).join("")));

How to split a word for getting a specific value in Javascript or Jquery? [duplicate]

How do I get the last segment of a url? I have the following script which displays the full url of the anchor tag clicked:
$(".tag_name_goes_here").live('click', function(event)
{
event.preventDefault();
alert($(this).attr("href"));
});
If the url is
http://mywebsite/folder/file
how do I only get it to display the "file" part of the url in the alert box?
You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substring() function to return the substring starting from that location:
console.log(this.href.substring(this.href.lastIndexOf('/') + 1));
That way, you'll avoid creating an array containing all your URL segments, as split() does.
var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
console.log(lastSegment);
window.location.pathname.split("/").pop()
The other answers may work if the path is simple, consisting only of simple path elements. But when it contains query params as well, they break.
Better use URL object for this instead to get a more robust solution. It is a parsed interpretation of the present URL:
Input:
const href = 'https://stackoverflow.com/boo?q=foo&s=bar'
const segments = new URL(href).pathname.split('/');
const last = segments.pop() || segments.pop(); // Handle potential trailing slash
console.log(last);
Output: 'boo'
This works for all common browsers. Only our dying IE doesn't support that (and won't). For IE there is a polyfills available, though (if you care at all).
Just another solution with regex.
var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);
Javascript has the function split associated to string object that can help you:
const url = "http://mywebsite/folder/file";
const array = url.split('/');
const lastsegment = array[array.length-1];
Shortest way how to get URL Last Segment with split(), filter() and pop()
function getLastUrlSegment(url) {
return new URL(url).pathname.split('/').filter(Boolean).pop();
}
console.log(getLastUrlSegment(window.location.href));
console.log(getLastUrlSegment('https://x.com/boo'));
console.log(getLastUrlSegment('https://x.com/boo/'));
console.log(getLastUrlSegment('https://x.com/boo?q=foo&s=bar=aaa'));
console.log(getLastUrlSegment('https://x.com/boo?q=foo#this'));
console.log(getLastUrlSegment('https://x.com/last segment with spaces'));
Works for me.
Or you could use a regular expression:
alert(href.replace(/.*\//, ''));
var urlChunks = 'mywebsite/folder/file'.split('/');
alert(urlChunks[urlChunks.length - 1]);
Returns the last segment, regardless of trailing slashes:
var val = 'http://mywebsite/folder/file//'.split('/').filter(Boolean).pop();
console.log(val);
I know, it is too late, but for others:
I highly recommended use PURL jquery plugin. Motivation for PURL is that url can be segmented by '#' too (example: angular.js links), i.e. url could looks like
http://test.com/#/about/us/
or
http://test.com/#sky=blue&grass=green
And with PURL you can easy decide (segment/fsegment) which segment you want to get.
For "classic" last segment you could write:
var url = $.url('http://test.com/dir/index.html?key=value');
var lastSegment = url.segment().pop(); // index.html
Get the Last Segment using RegEx
str.replace(/.*\/(\w+)\/?$/, '$1');
$1 means using the capturing group. using in RegEx (\w+) create the first group then the whole string replace with the capture group.
let str = 'http://mywebsite/folder/file';
let lastSegment = str.replace(/.*\/(\w+)\/?$/, '$1');
console.log(lastSegment);
Also,
var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);
Building on Frédéric's answer using only javascript:
var url = document.URL
window.alert(url.substr(url.lastIndexOf('/') + 1));
If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).
url.split('/').filter(function (s) { return !!s }).pop()
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));
Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.
If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);
To get the last segment of your current window:
window.location.href.substr(window.location.href.lastIndexOf('/') +1)
you can first remove if there is / at the end and then get last part of url
let locationLastPart = window.location.pathname
if (locationLastPart.substring(locationLastPart.length-1) == "/") {
locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
}
locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
Copied from this answer
// Store original location in loc like: http://test.com/one/ (ending slash)
var loc = location.href;
// If the last char is a slash trim it, otherwise return the original loc
loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/'));
var targetValue = loc.substring(loc.lastIndexOf('/') + 1);
targetValue = one
If your url looks like:
http://test.com/one/
or
http://test.com/one
or
http://test.com/one/index.htm
Then loc ends up looking like:
http://test.com/one
Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
// Store original location in loc like: http://test.com/one/ (ending slash)
let loc = "http://test.com/one/index.htm";
console.log("starting loc value = " + loc);
// If the last char is a slash trim it, otherwise return the original loc
loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substring(0,loc.length-1) : loc.substring(0,loc.lastIndexOf('/'));
let targetValue = loc.substring(loc.lastIndexOf('/') + 1);
console.log("targetValue = " + targetValue);
console.log("loc = " + loc);
Updated raddevus answer :
var loc = window.location.href;
loc = loc.lastIndexOf('/') == loc.length - 1 ? loc.substr(0, loc.length - 1) : loc.substr(0, loc.length + 1);
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
Prints last path of url as string :
test.com/path-name = path-name
test.com/path-name/ = path-name
I am using regex and split:
var last_path = location.href.match(/./(.[\w])/)[1].split("#")[0].split("?")[0]
In the end it will ignore # ? & / ending urls, which happens a lot. Example:
https://cardsrealm.com/profile/cardsRealm -> Returns cardsRealm
https://cardsrealm.com/profile/cardsRealm#hello -> Returns cardsRealm
https://cardsrealm.com/profile/cardsRealm?hello -> Returns cardsRealm
https://cardsrealm.com/profile/cardsRealm/ -> Returns cardsRealm
I don't really know if regex is the right way to solve this issue as it can really affect efficiency of your code, but the below regex will help you fetch the last segment and it will still give you the last segment even if the URL is followed by an empty /. The regex that I came up with is:
[^\/]+[\/]?$
I know it is old but if you want to get this from an URL you could simply use:
document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);
document.location.pathname gets the pathname from the current URL.
lastIndexOf get the index of the last occurrence of the following Regex, in our case is /.. The dot means any character, thus, it will not count if the / is the last character on the URL.
substring will cut the string between two indexes.
if the url is http://localhost/madukaonline/shop.php?shop=79
console.log(location.search); will bring ?shop=79
so the simplest way is to use location.search
you can lookup for more info here
and here
You can do this with simple paths (w/0) querystrings etc.
Granted probably overly complex and probably not performant, but I wanted to use reduce for the fun of it.
"/foo/bar/"
.split(path.sep)
.filter(x => x !== "")
.reduce((_, part, i, arr) => {
if (i == arr.length - 1) return part;
}, "");
Split the string on path separators.
Filter out empty string path parts (this could happen with trailing slash in path).
Reduce the array of path parts to the last one.
Adding up to the great Sebastian Barth answer.
if href is a variable that you are parsing, new URL will throw a TypeError so to be in the safe side you should try - catch
try{
const segments = new URL(href).pathname.split('/');
const last = segments.pop() || segments.pop(); // Handle potential trailing slash
console.log(last);
}catch (error){
//Uups, href wasn't a valid URL (empty string or malformed URL)
console.log('TypeError ->',error);
}
I believe it's safer to remove the tail slash('/') before doing substring. Because I got an empty string in my scenario.
window.alert((window.location.pathname).replace(/\/$/, "").substr((window.location.pathname.replace(/\/$/, "")).lastIndexOf('/') + 1));
Bestway to get URL Last Segment Remove (-) and (/) also
jQuery(document).ready(function(){
var path = window.location.pathname;
var parts = path.split('/');
var lastSegment = parts.pop() || parts.pop(); // handle potential trailing slash
lastSegment = lastSegment.replace('-',' ').replace('-',' ');
jQuery('.archive .filters').before('<div class="product_heading"><h3>Best '+lastSegment+' Deals </h3></div>');
});
A way to avoid query params
const urlString = "https://stackoverflow.com/last-segment?param=123"
const url = new URL(urlString);
url.search = '';
const lastSegment = url.pathname.split('/').pop();
console.log(lastSegment)

I need to run a function if the URL has a specific string that can also come up as part of another string using jQuery or Javascript

I need to write a function to perform an action only if the URL has a specific string. The issue that I am finding is that the string can come up in multiple instances as part of another string. I need the function to run when the string is ONLY "?page=1". What I am finding is that the function is also being run when the string contains a string like "?page=10" , "?page=11" , "?page=12" , etc... I only need it to be done if the string is "?page=1" - that's it. How do I do that? I've tried a couple of different ways, but it does not work. Any help is appreciated. Here is the latest code that I have used that is close...but no cigar.
var location = window.location.href;
if (location.indexOf("?page=1") > -1){
//Do something
};
?page is a GET parameter. It doesn't necessarily have to be first in the URL string. I suggest you properly decode the GET params and then base your logic on that. Here's how you can do that:
function unparam(qs) {
var params = {},
e,
a = /\+/g,
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); };
while (e = r.exec(qs)) {
params[d(e[1])] = d(e[2]);
}
return params;
}
var urlParams = unparam(window.location.search.substring(1));
if(urlParams['page'] == '1') {
// code here
}
Alternatively, a regex with word boundaries would have worked:
if(/\bpage=1\b/.test(window.location.search)) {
// code here
}
if(location .indexOf("?page=1&") != -1 || (location .indexOf("?page=1") + 7 == i.length) ) {
}
You could look at the character immediately following the string "?page=1" in the url. If it's a digit,you don't have a match otherwise you do. You could trivially do something like this:
var index = location.indexOf("?page=1"); //Returns the index of the string
var number = location.charCodeAt(index+x); //x depends on the search string,here x = 7
//Unicode values for 0-9 is 48-57, check if number lies within this range
Now that you have the Unicode value of the next character, you can easily deduce if the url contains the string you require or not. I hope this points you in the right direction.

Removing a string in javascript

I have a URL say
dummy URL
http://www.google.com/?v=as12&&src=test&img=test
Now I want to remove the &src=test& part alone.I know we can use indexof but somehow I could not get the idea of getting the next ampersand(&) and removing that part alone.
Any help.The new URL should look like
http://www.google.com/?v=as12&img=test
What about using this?:
http://jsfiddle.net/RMaNd/8/
var mystring = "http://www.google.com/?v=as12&&src=test&img=test";
mystring = mystring.replace(/&src=.+&/, ""); // Didn't realize it isn't necessary to escape "&"
alert(mystring);
This assumes that "any" character will come after the "=" and before the next "&", but you can always change the . to a character set if you know what it could be - using [ ]
This also assumes that there will be at least 1 character after the "=" but before the "&" - because of the +. But you can change that to * if you think the string could be "src=&img=test"
UPDATE:
Using split might be the correct choice for this problem, but only if the position of src=whatever is still after "&&" but unknown...for example, if it were "&&img=test&src=test". So as long as the "&&" is always there to separate the static part from the part you want to update, you can use something like this:
http://jsfiddle.net/Y7LdG/
var mystring1 = "http://www.google.com/?v=as12&&src=test&img=test";
var mystring2 = "http://www.google.com/?v=as12&&img=test&src=test";
var final1 = removeSrcPair(mystring1);
alert(final1);
var final2 = removeSrcPair(mystring2);
alert(final2);
function replaceSrc(str) {
return str.replace(/src=.*/g, "");
}
function removeSrcPair(orig) {
var the_split = orig.split("&&");
var split_second = the_split[1].split("&");
for (var i = split_second.length-1; i >= 0; i--) {
split_second[i] = replaceSrc(split_second[i]);
if (split_second[i] === "") {
split_second.splice(i, 1);
}
}
var joined = split_second.join("&");
return the_split[0] + "&" + joined;
}
This still assumes a few things - the main split is "&&"...the key is "src", then comes "=", then 0 or more characters...and of course, the key/value pairs are separated by "&". If your problem isn't this broad, then my first answer seems fine. If "src=test" won't always come first after "&&", you'd need to use a more "complex" Regex or this split method.
Something like:
url = "http://www.google.com/?v=as12&&src=test&img=test"
firstPart = url.split('&&')[0];
lastPart = url.split('&&')[1];
lastPart = lastPart.split('&')[1];
newUrl = firstPart+'&'+lastPart;
document.write(newUrl);
Details: Use the split method.
Solution Edited: I changed the below to test that the last query string exists
var url = "http://www.google.com/?v=as12&&src=test&img=test";
var newUrl;
var splitString = url.split('&');
if (splitString.length > 3)
{
newURL = splitString[0] + "&" + splitString[3];
}
else
{
newURL = splitString[0];
}

Remove a query argument from a URL in javascript

I'm trying to write a function that will remove a query argument from a url in javascript. I think I have it using regex, but I'm not sure if I've missed anything. Also, I can't shake the feeling that there was probably a better way to do this that didn't involve me messing around with regex half the day and running the risk of later finding out that I didn't take some kind of corner case into account.
remove_query_argument = function(url, arg){
var query_arg_regex;
// Remove occurences that come after '&' symbols and not the first one after the '?'
query_arg_regex = new RegExp('&' + arg + '=[^(?:&|$)]*', 'ig');
url = url.replace(query_arg_regex, '');
// remove the instance that the argument to remove is the first one
query_arg_regex = new RegExp('[?]' + arg + '[^(?:&|$)]*(&?)', 'i');
url = url.replace(query_arg_regex, function (match, capture) {
if( capture != '&' ){
return '';
}else{
return '?'
}
});
return url;
}
Does anyone see any problems with this code or would like to suggest a better implementation or way of going about this?
Thanks!
If you have a lot of URL-related operations, you better try this awesome js library https://github.com/medialize/URI.js
Given a percent-encoded URL, the following function will remove field-value pairs from its query string:
var removeQueryFields = function (url) {
var fields = [].slice.call(arguments, 1).join('|'),
parts = url.split( new RegExp('[&?](' + fields + ')=[^&]*') ),
length = parts.length - 1;
return parts[0] + '?' + (length ? parts[length].slice(1) : '');
}
Some examples:
var string = 'http://server/path/program?f1=v1&f2=v2';
removeQueryFields( string, 'f1' ); // 'http://server/path/program?f2=v2'
removeQueryFields( string, 'f2' ); // 'http://server/path/program?f1=v1'
removeQueryFields( string, 'f1', 'f2' ); // 'http://server/path/program'

Categories