Javascript - grab page name from url whether trailing slash or not - javascript

Not sure why this is stumping me. I need to grab the 'page' of a site. In my dev environment there is no trailing slash but on the staging server a trailing slash gets added. So, how do I return "page-name" regardless of if there's a trailing slash?
(Vanilla or jquery)
www.website.com/page-name
www.website.com/page-name/
My long solution... is there a shorter way?
let { href } = window.location;
let lastChar = href.substr(-1);
let ref;
if (lastChar === "/") {
ref = href.slice(0, -1);
} else {
ref = href;
}
let pageName = ref.split("/").pop();

You can use location.pathname to get the path, then split by / and get the second item in the resulting array:
const result = location.pathname.split("/")[1]

Regex possibly? get the last capture group.
let { href } = window.location;
const match = href.match(/\/([\w-]+)/g);
console.log(match[match.length - 1]);

use
const url=window.location.href.split('\//')[1]??'home'

Related

get first url segment with a javascript regex

I have this regexp to extract instagram.com usernames
const matches = value.match(
/^(?:#|(?:https?:\/\/)?(?:www\.)?instagr(?:\.am|am\.com)\/)?(\w+)\/?$/
);
console.log(matches[1])
It works fine with www.instagram.com/username but it doesn't work with www.instagram.com/username?ref=google
How can I exact only the username from the url?
Thanks for your help.
alternatively, do not use regex. e.g.
const url = "www.instagram.com/username?ref=google";
const oUrl = new URL("http://" + url);
console.log(oUrl.pathname.substring(1));
or
let url = "instagram.com/username?ref=google";
if (!url.startsWith("http://") || !url.startsWith("https://")) {
url = "http://" + url;
}
const oUrl = new URL(url);
console.log(oUrl.pathname.substring(1));
The $ at the end matches the end of the line, but the end of the username isn't necessarily the end of the line. To permit ? after the username as well, use (?:$|\?) instead of $:
^(?:#|(?:https?:\/\/)?(?:www\.)?instagr(?:\.am|am\.com)\/)?(\w+)\/?(?:$|\?)
https://regex101.com/r/pbpi74/1
You can also try a non-regex way using .substring. You may find it cleaner than regex.
It works with both URLs.
let username = url.substring(
url.lastIndexOf("/") + 1,
url.lastIndexOf("?") > 0? url.lastIndexOf("?") : url.length
);
Check fiddle:
https://jsfiddle.net/whx5otvp/

Slice URL to get the file name in Vue

I have a file url and I need to slice it for showing the file to the users. I have successfully sliced it using substring but what if the string to slice isn't fixed. Like this /media/users/3/sample.docx. I wanted to show sample.docx only so I used substring but what if the numbers before that, increases like the number 3? How can do it the better way?
sliceString(value) {
return value.substring(15)
}
{{sliceString(data.file)}}
Take the last index of /, add 1 to it and use in the substring method :
sliceString(value) {
let lastSlashIndex=value.lastIndexOf('/')
return value.substring(lastSlashIndex+1)
}
Example:
let url = 'sample.com/media/users/3/sample.docx'
let lastIndex= url.lastIndexOf('/');
console.log(url.substring(lastIndex+1))
Try to use value.lastIndexOf()
sliceString(value) {
return value.substring(value.lastIndexOf("/")+1)
}
{{sliceString(data.file)}}
Try using split:
const url = 'sample.com/media/users/3/sample.docx';
url = url.split('/');
len = url.length;
const sample = url[len-1];
console.log(sample) // 'sample.docx'
You can use regex to do it like that
const url = 'sample.com/media/users/3/sample.docx'
console.log(url.match(/[^\/]+$/)[0])
This should shrink the URL to just the filename even if there are query string parameters :
const fileString = 'file:///folder1/folder2/folder3/filename.extension?possibleQueries';
sliceURL = ((url) => {
lastChar = url.length;
if (url.lastIndexOf('?') > -1) {
lastChar = url.lastIndexOf('?');
};
return (url.substring(url.lastIndexOf("/") + 1, lastChar));
})
(fileString); // Expected output: "filename.extension"

Get values from window location . url

I have response url in window.location.href and I need the value for error, error_description and state from it
http://localhost:4200/#error=access_denied&error_description=AADB2C90118%3a+The+user+has+forgotten+their+password.%0d%0aCorrelation+ID%3a+a7916eb9-4404-4cc5-b5a3-ee3211237566%0d%0aTimestamp%3a+2018-02-05+09%3a19%3a07Z%0d%0alogin_hint%3a+kzahid%40opm.co.uk%0d%0a&state=da2d6e3c-cb6f-1d3b-909b-c6412325b3
I am using following code but getting null value
var messageType = new RegExp('[\?&]' + "error" + '=([^&#]*)').exec(window.location.href);
I need find this string from url "The user has forgotten their password"
Your problem here is that your URL parameters are preceded by a #, not a ?.
So, simply replace it and access the parameters using URLSearchParams#get():
var prevUrl = "http://localhost:4200/#error=access_denied&error_description=AADB2C90118%3a+The+user+has+forgotten+their+password.%0d%0aCorrelation+ID%3a+a7916eb9-4404-4cc5-b5a3-ee3211237566%0d%0aTimestamp%3a+2018-02-05+09%3a19%3a07Z%0d%0alogin_hint%3a+kzahid%40opm.co.uk%0d%0a&state=da2d6e3c-cb6f-1d3b-909b-c6412325b3";
var url = new URL(prevUrl.replace(/#/,'?'));
console.log(url.searchParams.get("error"));
console.log(url.searchParams.get("error_description"));
In a (modern) browser you can use the new URL() to parse your url and extract query parameters easily.
var location_url="http://localhost:4200/#error=access_denied&error_description=AADB2C90118%3a+The+user+has+forgotten+their+password.%0d%0aCorrelation+ID%3a+a7916eb9-4404-4cc5-b5a3-ee3211237566%0d%0aTimestamp%3a+2018-02-05+09%3a19%3a07Z%0d%0alogin_hint%3a+kzahid%40opm.co.uk%0d%0a&state=da2d6e3c-cb6f-1d3b-909b-c6412325b3";
//To make it work you have to replace "/#" with '?' so that new URL() constructor parses the url properly.
location_url=location_url.replace('\/#','?');
var url = new URL(location_url);
var error = url.searchParams.get("error");
console.log(error);
You could split by & and then split items by =.
// what you would do:
//const hash = location.hash;
// for demo purposes:
const hash = '#error=access_denied&error_description=AADB2C90118%3a+The+user+has+forgotten+their+password.%0d%0aCorrelation+ID%3a+a7916eb9-4404-4cc5-b5a3-ee3211237566%0d%0aTimestamp%3a+2018-02-05+09%3a19%3a07Z%0d%0alogin_hint%3a+kzahid%40opm.co.uk%0d%0a&state=da2d6e3c-cb6f-1d3b-909b-c6412325b3';
const hashParams = hash.substr(1).split('&')
.reduce((obj, groupStr) =>
Object.assign(obj, {
[groupStr.split('=')[0]]: groupStr.split('=')[1]
}), {});
console.log(hashParams);
console.log(hashParams.error_description);
use reg like this:
let url='http://localhost:4200/#error=access_denied&error_description=AADB2C90118%3a+The+user+has+forgotten+their+password.%0d%0aCorrelation+ID%3a+a7916eb9-4404-4cc5-b5a3-ee3211237566%0d%0aTimestamp%3a+2018-02-05+09%3a19%3a07Z%0d%0alogin_hint%3a+kzahid%40opm.co.uk%0d%0a&state=da2d6e3c-cb6f-1d3b-909b-c6412325b3';
let result=url.match(/error_description=([\s\S]*?)\./)[1].split('+');
result.shift();
console.log(result.join(' '));
If you still want to use a RegExp even though might be an overkill having the new options from the previous answers, you can use a RegExp like this:
const regex = /(error|error_description)=(.+?)&/g;
const str = `http://localhost:4200/#error=access_denied&error_description=AADB2C90118%3a+The+user+has+forgotten+their+password.%0d%0aCorrelation+ID%3a+a7916eb9-4404-4cc5-b5a3-ee3211237566%0d%0aTimestamp%3a+2018-02-05+09%3a19%3a07Z%0d%0alogin_hint%3a+kzahid%40opm.co.uk%0d%0a&state=da2d6e3c-cb6f-1d3b-909b-c6412325b3`;
let matches;
while ((matches = regex.exec(str)) !== null) {
if (matches.index === regex.lastIndex) {
regex.lastIndex++;
}
matches.forEach((match, groupIndex) => {
if (groupIndex === 1 )
console.log(`Param: ${match}`);
if (groupIndex === 2 )
console.log(`Value: ${match}`);
});
}
/(error|error_description)=(.+?)&/g
Here you have 2 capture groups inside the full match, so you can get separatedly the parameter name and its value.
(error|error_description) -> will match either error or error_description
(.+?) -> will match from 1 to any characters until it finds the next character match, stated in this case by &, as few times as possible and expanding as needed
The g (global modifier) will allow to return all the matches found.

javascript/jquery add trailing slash to url (if not present)

I'm making a small web app in which a user enters a server URL from which it pulls a load of data with an AJAX request.
Since the user has to enter the URL manually, people generally forget the trailing slash, even though it's required (as some data is appended to the url entered). I need a way to check if the slash is present, and if not, add it.
This seems like a problem that jQuery would have a one-liner for, does anyone know how to do this or should I write a JS function for it?
var lastChar = url.substr(-1); // Selects the last character
if (lastChar != '/') { // If the last character is not a slash
url = url + '/'; // Append a slash to it.
}
The temporary variable name can be omitted, and directly embedded in the assertion:
if (url.substr(-1) != '/') url += '/';
Since the goal is changing the url with a one-liner, the following solution can also be used:
url = url.replace(/\/?$/, '/');
If the trailing slash exists, it is replaced with /.
If the trailing slash does not exist, a / is appended to the end (to be exact: The trailing anchor is replaced with /).
url += url.endsWith("/") ? "" : "/"
I added to the regex solution to accommodate query strings:
http://jsfiddle.net/hRheW/8/
url.replace(/\/?(\?|#|$)/, '/$1')
This works as well:
url = url.replace(/\/$|$/, '/');
Example:
let urlWithoutSlash = 'https://www.example.com/path';
urlWithoutSlash = urlWithoutSlash.replace(/\/$|$/, '/');
console.log(urlWithoutSlash);
let urlWithSlash = 'https://www.example.com/path/';
urlWithSlash = urlWithSlash.replace(/\/$|$/, '/');
console.log(urlWithSlash);
Output:
https://www.example.com/path/
https://www.example.com/path/
It replaces either the trailing slash or no trailing slash with a trailing slash. So if the slash is present, it replaces it with one (essentially leaving it there); if one is not present, it adds the trailing slash.
You can do something like:
var url = 'http://stackoverflow.com';
if (!url.match(/\/$/)) {
url += '/';
}
Here's the proof: http://jsfiddle.net/matthewbj/FyLnH/
The URL class is pretty awesome - it helps us change the path and takes care of query parameters and fragment identifiers
function addTrailingSlash(u) {
const url = new URL(u);
url.pathname += url.pathname.endsWith("/") ? "" : "/";
return url.toString();
}
addTrailingSlash('http://example.com/slug?page=2');
// result: "http://example.com/slug/?page=2"
You can read more about URL on MDN
Before finding this question and it's answers I created my own approach. I post it here as I don't see something similar.
function addSlashToUrl() {
//If there is no trailing shash after the path in the url add it
if (window.location.pathname.endsWith('/') === false) {
var url = window.location.protocol + '//' +
window.location.host +
window.location.pathname + '/' +
window.location.search;
window.history.replaceState(null, document.title, url);
}
}
Not every URL can be completed with slash at the end. There are at least several conditions that do not allow one:
String after last existing slash is something like index.html.
There are parameters: /page?foo=1&bar=2.
There is link to fragment: /page#tomato.
I have written a function for adding slash if none of the above cases are present. There are also two additional functions for checking the possibility of adding slash and for breaking URL into parts. Last one is not mine, I've given a link to the original one.
const SLASH = '/';
function appendSlashToUrlIfIsPossible(url) {
var resultingUrl = url;
var slashAppendingPossible = slashAppendingIsPossible(url);
if (slashAppendingPossible) {
resultingUrl += SLASH;
}
return resultingUrl;
}
function slashAppendingIsPossible(url) {
// Slash is possible to add to the end of url in following cases:
// - There is no slash standing as last symbol of URL.
// - There is no file extension (or there is no dot inside part called file name).
// - There are no parameters (even empty ones — single ? at the end of URL).
// - There is no link to a fragment (even empty one — single # mark at the end of URL).
var slashAppendingPossible = false;
var parsedUrl = parseUrl(url);
// Checking for slash absence.
var path = parsedUrl.path;
var lastCharacterInPath = path.substr(-1);
var noSlashInPathEnd = lastCharacterInPath !== SLASH;
// Check for extension absence.
const FILE_EXTENSION_REGEXP = /\.[^.]*$/;
var noFileExtension = !FILE_EXTENSION_REGEXP.test(parsedUrl.file);
// Check for parameters absence.
var noParameters = parsedUrl.query.length === 0;
// Check for link to fragment absence.
var noLinkToFragment = parsedUrl.hash.length === 0;
// All checks above cannot guarantee that there is no '?' or '#' symbol at the end of URL.
// It is required to be checked manually.
var NO_SLASH_HASH_OR_QUESTION_MARK_AT_STRING_END_REGEXP = /[^\/#?]$/;
var noStopCharactersAtTheEndOfRelativePath = NO_SLASH_HASH_OR_QUESTION_MARK_AT_STRING_END_REGEXP.test(parsedUrl.relative);
slashAppendingPossible = noSlashInPathEnd && noFileExtension && noParameters && noLinkToFragment && noStopCharactersAtTheEndOfRelativePath;
return slashAppendingPossible;
}
// parseUrl function is based on following one:
// http://james.padolsey.com/javascript/parsing-urls-with-the-dom/.
function parseUrl(url) {
var a = document.createElement('a');
a.href = url;
const DEFAULT_STRING = '';
var getParametersAndValues = function (a) {
var parametersAndValues = {};
const QUESTION_MARK_IN_STRING_START_REGEXP = /^\?/;
const PARAMETERS_DELIMITER = '&';
const PARAMETER_VALUE_DELIMITER = '=';
var parametersAndValuesStrings = a.search.replace(QUESTION_MARK_IN_STRING_START_REGEXP, DEFAULT_STRING).split(PARAMETERS_DELIMITER);
var parametersAmount = parametersAndValuesStrings.length;
for (let index = 0; index < parametersAmount; index++) {
if (!parametersAndValuesStrings[index]) {
continue;
}
let parameterAndValue = parametersAndValuesStrings[index].split(PARAMETER_VALUE_DELIMITER);
let parameter = parameterAndValue[0];
let value = parameterAndValue[1];
parametersAndValues[parameter] = value;
}
return parametersAndValues;
};
const PROTOCOL_DELIMITER = ':';
const SYMBOLS_AFTER_LAST_SLASH_AT_STRING_END_REGEXP = /\/([^\/?#]+)$/i;
// Stub for the case when regexp match method returns null.
const REGEXP_MATCH_STUB = [null, DEFAULT_STRING];
const URL_FRAGMENT_MARK = '#';
const NOT_SLASH_AT_STRING_START_REGEXP = /^([^\/])/;
// Replace methods uses '$1' to place first capturing group.
// In NOT_SLASH_AT_STRING_START_REGEXP regular expression that is the first
// symbol in case something else, but not '/' has taken first position.
const ORIGINAL_STRING_PREPENDED_BY_SLASH = '/$1';
const URL_RELATIVE_PART_REGEXP = /tps?:\/\/[^\/]+(.+)/;
const SLASH_AT_STRING_START_REGEXP = /^\//;
const PATH_SEGMENTS_DELIMITER = '/';
return {
source: url,
protocol: a.protocol.replace(PROTOCOL_DELIMITER, DEFAULT_STRING),
host: a.hostname,
port: a.port,
query: a.search,
parameters: getParametersAndValues(a),
file: (a.pathname.match(SYMBOLS_AFTER_LAST_SLASH_AT_STRING_END_REGEXP) || REGEXP_MATCH_STUB)[1],
hash: a.hash.replace(URL_FRAGMENT_MARK, DEFAULT_STRING),
path: a.pathname.replace(NOT_SLASH_AT_STRING_START_REGEXP, ORIGINAL_STRING_PREPENDED_BY_SLASH),
relative: (a.href.match(URL_RELATIVE_PART_REGEXP) || REGEXP_MATCH_STUB)[1],
segments: a.pathname.replace(SLASH_AT_STRING_START_REGEXP, DEFAULT_STRING).split(PATH_SEGMENTS_DELIMITER)
};
}
There might also be several cases when adding slash is not possible. If you know some, please comment my answer.
For those who use different inputs: like http://example.com or http://example.com/eee. It should not add a trailling slash in the second case.
There is the serialization option using .href which will add trailing slash only after the domain (host).
In NodeJs,
You would use the url module like this:
const url = require ('url');
let jojo = url.parse('http://google.com')
console.log(jojo);
In pure JS, you would use
var url = document.getElementsByTagName('a')[0];
var myURL = "http://stackoverflow.com";
console.log(myURL.href);

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