Rewrite URL Prefix Using Javascript / Jquery - javascript

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)

Related

Node.js get all occurrences of a substring in a string

I have a string in Node.js Runtime e.g
var content = "my content contain some URL like https://this.me/36gD6d3 or https://this.me/39Jwjd";
How can I read each https://this.me/36gD6d3 and https://this.me/39Jwjd to replace it with another URL?
A forEach loop or something similar would be best. :-)
What I need is to make a request to each of that URL to get the real URL behind the shorten URL. That's not the problem.
Before and after each of that URLs is neither a whitespace or a ..
Domain https://this.me/ is constant but the IDs 39Jwjd, 36gD6d3 are changing.
Looking forward to your answers! :)
You can use regex to find occurrences of this URL.
var content = "my content contain some URL like https://this.me/36gD6d3 or https://this.me/39Jwjd";
console.log(content.match(/https:\/\/this\.me\/[a-zA-Z0-9]+/g))
This outputs:
[
"https://this.me/36gD6d3",
"https://this.me/39Jwjd"
]
In order to replace the found occurrences, use replace() function.
var content = "my content contain some URL like https://this.me/36gD6d3 or https://this.me/39Jwjd";
console.log(content.replace(/https:\/\/this\.me\/[a-zA-Z0-9]+/g, "<Replaced URL here>"))
Output:
my content contain some URL like <Replaced URL here> or <Replaced URL here>
If you want to replace the occurrences depending on the previous value, you could either use substitution or pass replacement function as the second argument.
Learn more on String.prototype.replace function at MDN
If you want your replace to be asynchronous (which I'm guessing is the case when you lookup the full URL), you could do something like this:
(async () => {
const str = "my content contain some URL like https://this.me/36gD6d3 or https://this.me/39Jwjd",
res = await replaceAllUrls(str);
console.log(res);
})();
function replaceAllUrls(str) {
const regex = /https?:\/\/this\.me\/[a-zA-Z0-9_-]+/g,
matches = str.match(regex) || [];
return Promise.all(matches.map(getFullUrl)).then(values => {
return str.replace(regex, () => values.shift());
});
}
function getFullUrl(u) {
// Just for the demo, use your own
return new Promise((r) => setTimeout(() => r(`{{Full URL of ${u}}}`), 100));
// If it fails (you cannot get the full URL),
// don't forget to catch the error and return the original URL!
}

How to get parts of a URL string using Javascript?

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.

Replace the url parameter value using js

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

How do i match text after a specific character?

I have a url that looks like this:
http://mysite/#/12345
How do I retrieve the text using regex after the /#/ which is essentially a token that I would like to use elsewhere in my javascript application?
Thanks.
You don't need regex here, just String#substr using String#indexOf:
var s = 'http://mysite/#/12345';
var p ='/#/'; // search needle
var r= s.substr(s.indexOf(p) + p.length);
//=> 12345
Let the browser do it for you
var parser = document.createElement('a');
parser.href = "http://mysite/#/12345";
alert(parser.hash.substring(2)); //This is just to remove the #/ at the start of the string
JSFiddle: http://jsfiddle.net/gibble/uvhqa4yv/
Try with JavaScript String methods.
var str='http://mysite/#/12345';
alert(str.substring(str.lastIndexOf("/#/")+3));
You can try with String'smatch() method as well that uses regex expression.
Just get the matched group from index 1 that is captured by enclosing inside the parenthesis (...)
var str='http://mysite/#/12345';
alert(str.match(/\/#\/(.*)$/)[1]);
Using the browser to parse the URL and getting the hash would probably be most reliable and would work with any valid URL
var url = 'http://mysite/#/12345';
var ele = document.createElement('a');
ele.href = url;
var result = ele.hash.slice(2);
FIDDLE
or you can just split and pop it
var result = url.split('#/').pop();

Javascript remove characters utill 3 slash /

Whats the best to way, based on the input below, to get everything in the url after the domain:
var url = "http://www.domain.com.uk/sadsad/asdsadsad/asdasdasda/?asda=ggy";
var url = "http://www.domain.com.uk/asdsadsad/asdasdasda/#45435";
var url = "http://www.domain.com.uk/asdasdasda/?324324";
var url = "http://www.domain.com.uk/asdasdasda/";
The output:
url = "/sadsad/asdsadsad/asdasdasda/?asda=ggy";
url = "/asdsadsad/asdasdasda/#45435";
url = "/asdasdasda/?324324";
UPDATE: the domain its not always the same. (sorry)
Thx
You should really parse the URI.
http://stevenlevithan.com/demo/parseuri/js/
Every absolute URL consists of a protocol, separated by two slashes, followed by a host, followed by a pathname. An implementation can look like:
// Search for the index of the first //, then search the next slash after it
var slashOffset = url.indexOf("/", url.indexOf("//") + 2);
url = url.substr(slashOffset);
If the domain is always the same, a simple replace will work fine:
var url = "http://www.domain.com.uk/sadsad/asdsadsad/asdasdasda/?asda=ggy";
var afterDomain = url.replace("^http://www.domain.com.uk/", "");
You could also use RegEx:
var url = "http://www.domain.com.uk/sadsad/asdsadsad/asdasdasda/?asda=ggy";
var afterDomain = url.replace(/^[^\/]*(?:\/[^\/]*){2}/, "");
Assuming this is in the browser, creating an anchor element will do a lot of magic on your behalf:
var a=document.createElement('a');
a.href="http://somedomain/iouhowe/ewouho/wiouhfe?jjj";
alert(a.pathname + a.search + a.hash); // /iouhowe/ewouho/wiouhfe?jjj

Categories

Resources