How to get the last two characters of url with jQuery? - javascript

I have a url with the following format:
base/list.html?12
and I want to create a variable which will be equal to the digits after the question mark in the url of the page. Something like:
var xxx = anything after the ? ;
Then I need to load dynamic data into that page using this function:
if(document.URL.indexOf(xxx) >= 0){
alert('Data loaded!');
}
How can I achieve this? and are the codes above correct?
Thanks

You can use split to get the characters after ? in the url
var xxx = 'base/list.html?12';
var res = xxx.split('?')[1];
or for current page url
var res = document.location.href.split('?')[1];

res = document.location.href.split('?')[1];

Duplicate of 6644654.
function parseUrl( url ) {
var a = document.createElement('a');
a.href = url;
return a;
}
var search = parseUrl('base/list.html?12').search;
var searchText = search.substr( 1 ); // removes the leading '?'

document.location.search.substr(1) would also work

Related

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

Check if URL has anything after second "/" using javascript / jquery

So I have a completely variable url:
www.whatever.com/something/pagename
I need something to happen on the homepage of the websites and not on any of the other pages. Sometimes the homepage has a "something" in the url and sometimes it doesn't, so I need to find out if "pagename" exists, whatever it may be.
all values in the url vary so i can't simply search for a string in the url..
Is this possible to do this using only JS / JQuery?
Thanks
Split is the solution:
var exampleURL = "www.whatever.com/something/pagename";
var pageName = exampleURL.split("/")[2];
console.log(pageName);
//OUT -> pagename
Split the URL and then check the length of the result.
var split_url = url.split('/');
if (split_url.length > 2) {
// URL is like www.whatever.com/something/pagename...
} else {
// URL is just www.whatever.com or www.whatever.com/something
}
Another way is with a regular expression that matches a URL with two slashes:
if (url.match(/\/.*\//)) {
// URL contains two slashes
} else {
// URL has at most one slash
}
You could do a regex check:
/^[^\/\s]*(\/\/)?[^\/\s]+\/[^\/\s]+[^\/]+\/[^\/\s]+$/.test('www.whatever.com/something/pagename')
demo:
https://regex101.com/r/vF1bH8/1
The question is not really clear, but to answer the title literally https://jsfiddle.net/jgfeymk1/
function after2ndFSlash(inpu){
var pieces = inpu.split('/');
var output = document.getElementById('output');
if(pieces.length>2){
output.innerHTML += 'true<br/>';
}
else{
output.innerHTML += 'false<br/>';
}
}
Assuming that url string has protocol included ... http(s):// ... you can pass it to href of an <a> element and access the pathname property
var url ='http://www.whatever.com/something/pagename'
var a = document.createElement('a');
a.href = url;
var pathParts = a.pathname.replace(/^\//,'').split('/');//["something","pagename"]
alert(pathParts[1]); //"pagename"

remove a specific area from url using jquery

I have a URL such as http://myurleg.com/ar/Message.html and I want to replace ar with en in it, after clicking on it.
It means that if my url is: http://myurleg.com/ar/Message.html
After click it should become: http://myurleg.com/en/Message.html
I just tried
<script>
$(document).ready(function () {
$('#lng_flip').click(function () {
var url = window.location.href.split('/')[0];
});
});
</script>
Can anyone help?
You can user string replace :
var str = "http://myurleg.com/ar/Message.html";
document.write(str);
var res = str.replace("/ar/", "/fr/");
document.write('<br /> Result : ' + res );
var current = location.pathname.substring(1, 3);
var flipped = current == 'en' ? 'ar' : 'en';
location.pathname = '/' + flipped + location.pathname.substring(3);
Try this
var str = 'http://myurleg.com/ar/Message.html';
var txt = str.replace(/ar/i,"en");
Or in your case
var url = window.location.href;
window.location.href = url.replace(/ar/i,"en");
A general solution, supporting any two-letter language code at the beginning of the path, would be:
location.href = location.href.replace(/(\/\/.*?\/)\w{2}(.*)/, '$1en$2');
Though sometimes it makes more sense to only manipulate location.pathname:
location.pathname = location.pathname.replace(/\/\w{2}(.*)/, '/en$1');
Replace ar in split('/') array with en and join it again using join('/')
var url ='http://myurleg.com/ar/Message.html'.split('/');
url[3]='en';
url=url.join('/');
document.write(url);

Single regexp to get page URL but exclude port number from a full URL

I'm trying to come up with a regexp to get the page URL from the full URL but exclude a possible port number from it. So far I came up with the following JS:
var res = url.match(/^.*\:\/\/(?:www2?.)?([^?#]+)/i);
if(res)
{
var pageURL = res[1];
console.log(pageURL);
}
If I call it for this:
var url = "http://www.example.com/php/page.php?what=sw#print";
I get the correct answer: example.com/php/page.php
But if I do:
var url = "http://www.example.com:80/php/page.php?what=sw#print";
I need it to return example.com/php/page.php instead of example.com:80/php/page.php.
I can remove it with the second regexp, but I was curious if I could do it with just one (for speed)?
You can modify your regex to this:
/^.*\:\/\/(?:www2?.)?([^/:]+)(?:[^:]*:\d+)?([^?#]+)/i
RegEx Demo
It will return 2 matches:
1: example.com
2: /php/page.php
as match[1] and match[2] respectively for both inputs that you can concatenate.
http://www.example.com/php/page.php?what=sw#print
OR
http://www.example.com:80/php/page.php?what=sw#print
Update: Here are performance results on jsperf.com that shows regex method is fastest is of all.
Keep it simple:
~ node
> "http://www.example.com:3000/php/page.php?what=sw#print".replace(/:\d+/, '');
'http://www.example.com/php/page.php?what=sw#print'
> "http://www.example.com/php/page.php?what=sw#print".replace(/:\d+/, '');
'http://www.example.com/php/page.php?what=sw#print'
Why would you use a regex at all?
EDIT:
As pointed out by #c00000fd: Because document might not be available and document.createElement is very slow compared to RegExp - see:
http://jsperf.com/url-parsing/5
http://jsperf.com/hostname-from-url
Nevertheless I will leave my original answer for reference.
ORIGINAL ANSWER:
Instead you could just use the Anchor element:
Fiddle:
http://jsfiddle.net/12qjqx7n/
JS:
var url = 'http://foo:bar#www.example.com:8080/php/page.php?what=sw#print'
var a = document.createElement('a');
a.href = url;
console.log(a.hash);
console.log(a.host);
console.log(a.hostname);
console.log(a.origin);
console.log(a.password);
console.log(a.pathname);
console.log(a.port);
console.log(a.protocol);
console.log(a.search);
console.log(a.username);
Additional information:
http://www.w3schools.com/jsref/dom_obj_anchor.asp
How about a group for matching the port, if present?
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.match(/^.*\:\/\/(?:www2?.)?([^?#\/:]+)(\:\d+)?(\/[^?#]+)/i);
if(res)
{
var pageURL = res[1]+res[3];
console.log(res, pageURL);
}
Try
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.split(/\w+:\/\/+\w+\.|:+\d+|\?.*/).join("");
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.split(/\w+:\/\/+\w+\.|:+\d+|\?.*/).join("");
document.body.innerText = res;
You could use replace method to modify your original string or Url,
> var url = "http://www.example.com/php/page.php?what=sw#print";
undefined
> var url1 = "http://www.example.com:80/php/page.php?what=sw#print";
undefined
> url.replace(/^.*?:\/\/(?:www2?.)?([^/:]+)(?::\d+)?([^?#]+).*$/g, "$1$2")
'example.com/php/page.php'
> url1.replace(/^.*?:\/\/(?:www2?.)?([^/:]+)(?::\d+)?([^?#]+).*$/g, "$1$2")
'example.com/php/page.php'
DEMO

Extract part of current url to use in javascript function

hoping someone who knows a bit about javascript maybe able to help me. I need to extract part of the url of my pagepage to use in a javascript function and append to a url. ( it's for a power reviews setup.) the portion i need to extract is the number of the example below ie. www.mydomain.com/my-product-could-be-i950.html -- so would just need the 950 part.. the number part could be 2,3,4 characters. I then need to append this to the url www.mydomain.com/write-a-review.html?pr_page_id=950
could anyone help, it's a bit beyond me this one to be honest..
Many thanks.. Nathan
var num = location.pathname.match(/(\d+)\.html$/);
if( num ) {
var url = 'www.mydomain.com/write-a-review.html?pr_page_id=' + num[1];
}
Try this:
<script type="text/javascript">
function changeURL()
{
var szURL = location.pathname;
szURL = "www.mydomain.com/my-product-could-be-i950.html";
var num = szURL.replace(/\D/gi, "");
szURL = "www.mydomain.com/write-a-review.html?pr_page_id=" + num;
//Set URL
}
</script>
you could use regex:
var re = /i([0-9]{2,4})\.html$/;
var m = document.location.match(re);
if (m){
document.location.href = 'http://www.mydomain.com/write-a-review.html?pr_page_id='+m[1];
}
//current page URL
cur = window.location
//regex to match your number
regex = /i[0-9]{2,4}\.html/;
//your number
num = cur.match(regex);
alert(num);
Not tested, Note that the variable num could be an array.

Categories

Resources