I have this URL:
var url = "mysite.com/categorias/#tab-cultura/folclore/";
now I want to get 2 string from that URL:
#tab-cultura and folclore
how can I get it using Javascript?
url.split('#')[0];
It seems this split is not the right solution:(
"Split" can be correct way to approach this. Pls see below
var url = "mysite.com/categorias/#tab-cultura/folclore/";
let [val1, val2] = url.split('#')[1].split('/')
console.log(val1, val2)
You need to split your URL by / delimiter instead
var url = "mysite.com/categorias/#tab-cultura/folclore/";
var parts = url.split('/');
console.log(parts[2]);
console.log(parts[3]);
Also you can use regex if you don't know position of # in URL
var url = "mysite.com/categorias/category1/category2/#tab-cultura/folclore/";
var parts = url.match(/(#[^\/]+)\/([^\/]+)/);
console.log(parts[1]);
console.log(parts[2]);
With JavaScript’s String.prototype.split function:
var url = "mysite.com/categorias/#tab-cultura/folclore/";
var fields = input.split('/');
var first = fields[0];
var second = fields[1];
var third = fields[2];
var fourth = fields[3];
You can use split('/') like so:
var url = "mysite.com/categorias/#tab-cultura/folclore/";
let [, ,tabCultura, folclore] = url.split('/');
console.log(tabCultura);
console.log(folclore);
Using Array.split() will probably get you what you need — for now, but URLs are inherently quite complicated and you want to make sure the code will function the same way on different servers with variable query parameters etc. It may be more reliable to use built in browser functionality:
const hash = new URL("http://example.com/categorias/#tab-cultura/folclore/").hash
// => "#tab-cultura/folclore/"
hash.split('/')
// => ['#tab-cultura', 'folclore', '']
hash.split('/').filter(i=>i)
// => ['#tab-cultura', 'folclore']
Note: new URL() is not available in IE, but can be polyfilled.
Related
I am retrieving some data from an external API using javascript, I'm then displaying this data on a HTML page.
Within this returned data is a URL, it's in the following format;
var url = https://img.evbuc.com/moreStuff
I need to rewrite this URL so that it's prefixed with www, like this;
var url = https://www.img.evbuc.com/moreStuff
I want to achieve this using either javascript or jquery.
How can I achieve this? An explanation of the correct code would be great too.
You don't need regex for this you can simply use URL api
let url = "https://img.evbuc.com/moreStuff"
let parsed = new URL(url)
parsed.host = parsed.host.startsWith('www.') ? parsed.host : "www."+ parsed.host
console.log(parsed)
You can use a regular expression to search and replace.
Following example also works with:
http://img.evbuc.com/moreStuff
//img.evbuc.com/moreStuff
https://img.evbuc.com/moreStuff//someMoreStuff
function prependUrl(url) {
return url.replace(/^([^\/]*)(\/\/)(.*)/, '$1//www.$3');
}
const urls = [
'https://img.evbuc.com/moreStuff',
'http://img.evbuc.com/moreStuff',
'//img.evbuc.com/moreStuff',
'https://img.evbuc.com/moreStuff//someMoreStuff'
];
urls.forEach((url) => console.log(`${ url } -> ${ prependUrl(url) }`));
The regular expression contains 3 capturing groups:
Select everything up to the first / (excluding)
Select the // (for protocol root)
Select the rest
The replacement value takes everything up to the first / (which may be an empty string as well)
Replace the // with //www.
Append the rest
If you want something that will work with any protocol, try this regex:
var url = "https://img.evbuc.com/moreStuff"
var new_url = url.replace(/^([a-zA-Z][a-zA-Z0-9\.\+\-]*):\/\//, "$1://www.")
console.log('new URL: ', new_url)
Simple string operations:
var url = 'https://img.evbuc.com/moreStuff'
var newUrl = url.split('//')[0] + '//www.' + url.split('//')[1]
console.log(newUrl)
and yet another way to do this is like this:
var url = 'https://img.evbuc.com/moreStuff'
var newUrl = url.replace('https://', 'https://www.')
console.log(newUrl)
I have this url
/application-form?targetDate=2018-03-21
I want to get the string after the equal sign
How to do that?
use split and array
var param = "/application-form?targetDate=2018-03-21";
var items = param.split("=");
var arr1 = items[0];
var arr2 = items[1];
var result = arr2;
Using lastIndexOf and substr methods of string.
const url = '/application-form?targetDate=2018-03-21';
const lastEqualSignIndex = url.lastIndexOf('=');
const datePart = url.substr(lastEqualSignIndex + 1);
console.log(datePart); // -> '2018-03-21'
Edited: multiple query parameters support
Using match method of string:
const [, targetDateValue] = '/application-form?targetDate=2018-03-21'.match(/[\?&]targetDate=([^&#]*)/);
console.log(targetDateValue); // -> '2018-03-21'
You can use URLSearchParams for this. It's a parser for query strings.
Here's how it's used:
new URLSearchParams('?targetDate=2018-03-21').get('targetDate')
// or if you want to use your URL as-is:
new URLSearchParams('/application-form?targetDate=2018-03-21'.split('?')[1]).get('targetDate')
Be aware that this is not supported on IE. For cross-browser variations of this, you can have a look at this answer.
I have a URL like below.
something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false
I want to replace the value of parameter showHiddenElements to some new value.
for e.g. exising value in URL -> showHiddenElements=false
I want to change it through JavaScript to -> showHiddenElements=true
Please advise.
Edit:
showHiddenElements may not always be false. And In some cases it may not be available.
Use the URL Object:
const url = new URL('http://something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false');
url.searchParams.delete('showHiddenElements');
url.searchParams.append('showHiddenElements', true);
So you just delete the parameter and update it with the new one (not the most elegant)
Docs here: https://developer.mozilla.org/fr/docs/Web/API/URL
You could use String.replace for that:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
newUrl = url.replace('showHiddenElements=false', 'showHiddenElements=true');
You could also do it fancy and use regex:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
newUrl = url.replace(/showHiddenElements=false$/, 'showHiddenElements=true');
The regex would only match showHiddenElements=false if it's on the end of the URL
To see if it's available you could use regex too:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
// If the url doesn't have a showHiddenElements=__any_word__
if (!url.match(/showHiddenElements=\w+/)) {
url = url + 'showHiddenElements=false';
}
var url = "something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false";
alert("Before: "+url);
url = url.replace("&showHiddenElements=false","&showHiddenElements=true");
alert("After: "+url);
//Console.log clips the end so we can't see the result :(
Maybe something liket this:
var loc = window.location.href;
var newLoc = loc.Replace('showHiddenElements=true', 'showHiddenElements=false')
A JavaScript Regular Expression should help if you are just treating the URL as a string.
var str = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
var res = str.replace(/showHiddenElements/i, 'true');
console.log(res);
I am declaring the current URL variable as
var vFullURL = (document.URL);
This is added to the table with the correct URL string.
When I then try the following:
var vURL = vFullURL.split("/");
or
var vURL = vFullURL.toString.split("/");
The URL returns as System.Object[]
Does anyone know how I can split the URL?
You need to call toString() after you split it, not before.
var vFullURL = document.URL;
var vURL = vFullURL.split('/').toString();
Results in (for this page, as example): "http:,,stackoverflow.com,questions,27786939,javascript-cannot-split-sharepoint-url-showing-as-system-object,27787020#27787020"
I would like to extract the following String :
http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg
from this String :
https://s1.yimg.com/bt/api/res/1.2/yqEp3ogcVvfSaDSSIq.Llg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg
And before, extract, i would like to check if the global String contains more than one time "http" to be sure to extract the jpg only when needed.
How can i do that ?
Extract the data like this:
var myStr = "https://s1.yimg.com/bt/api/res/1.2/yqEp3ogcVvfSaDSSIq.Llg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg"
var splittedStr = myStr.split("-");
var extractedStr = splittedStr[3].slice(1);
To find out how many "http" is present in the string:
var count = (myStr.match(/http/g)).length;
Hopes it helps
var source = "https://s1.yimg.com/bt/api/res/1.2/yqEp3ogcVvfSaDSSIq.Llg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg"
var temp = source.replace("https","http").split("http");
var result = 'http'+temp[2];
use split()
var original = "https://s1.yimg.com/bt/api/res/1.2/yqEp3ogcVvfSaDSSIq.Llg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg";
original = original.split('-/');
alert($(original)[original.length-1]);
your require URL shows in alert dialog
You can use regex :
str.match(/(http?:\/\/.*\.(?:png|jpg))/i)
FIDDLE