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);
Related
using jQuery; to add something to a url after the last /
for example add sale to:
/gender/category/brand/
so it becomes:
/gender/category/brand/sale
However due to the way the URL's are generated and built I can't just always say 'add it to the end of a URL' as there are sometimes ?query strings on the end for example:
/gender/category/brand/?collection=short&colour=red
I just can't figure out how I can add sale after the final / and always before a ?query string if one exists.
Searching through stackoverflow I've seen some bits about extracting content after the last / but not this, is this possible? I really would appreciate help getting this sorted.
EDIT - The solution
Thanks too all for your help but I was able to adapt Shree's answer the easiest to get this which did what I needed:
if(window.location.href.indexOf("sale") > -1) {
} else {
var raw = window.location.href;
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
window.location.href = newUrl;
}
Use substring with lastIndexOf.
var raw = '/gender/category/brand/?collection=short&colour=red';
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
console.log(newUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In vanilla javascript
var a = "/gender/category/brand/?collection=short&colour=red";
var lastIndexPosition = a.lastIndexOf('/');
a = a.substring(0,lastIndexPosition+1)
+"sale"
+a.substring(lastIndexPosition+1 , a.length);
console.log(a);
By using a reusable function in Javascript:
You can use lastIndexOf and get the last '/' index position and append your new data there.
The lastIndexOf() method returns the position of the last occurrence
of a specified value in a string.
Using this you can send any parameter into function there by it is reusable.
function insert(main_string, ins_string, pos) {
return main_string.slice(0, pos) + ins_string + main_string.slice(pos);
}
var url = "/gender/category/brand/?collection=short&colour=red"
url = insert(url, 'sale', url.lastIndexOf("/") + 1)
console.log(url)
Here is a working DEMO
An alternative, use .split("?") to separate at the ? then combine them back, eg:
// Example with querystring
var url = '/gender/category/brand/?collection=short&colour=red'
var parts = url.split("?");
var newurl = parts[0] + "sale" + "?" + (parts[1]||"")
console.log(newurl)
// Test without querystring
var url = '/gender/category/brand/'
var parts = url.split("?");
var newurl = parts[0] + "sale" + (parts[1]||"")
console.log(newurl)
The (parts[1]||"") handles the case where there isn't a querystring.
How can I remove this string from href and update it ?
Example Url:
"localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,Products/Name,ID,People/FirstName,Products/Price,People/LastName&$expand=People"
What I am trying:
var stringToRemove = "Products" + "/";
var url = $("#qUrl").attr("href");
url = url.replace('/(' + stringToRemove + '\/\w+,)/g', '');
$("#qUrl").attr("href", url);
What I want:
"localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,ID,People/FirstName,People/LastName&$expand=People"
Update
Please don't hard code
If you are looking to remove all Products/..., than RegEx is /Products\/.*?,/g
Take a note that RegExp is written as is - without surrounding it with quotes.
var str = 'localhost:21088/WcfDataService1.svc/Clients?$top=20&$select=Name,Products/Name,ID,People/FirstName,Products/Price,People/LastName&$expand=People';
console.log(str.replace(/Products\/\w+,?/g, ''));
/**
* Replace with variable string
*/
var key = 'Products'; // Come from external source, not hardcoded.
var pattern = new RegExp(key+'/\\w+,?', 'g'); // Without start and end delimiters!
console.log(str.replace(pattern, ''));
var stringToRemove = "Products" + "/";
var url = $("#qUrl").attr("href");
url = url.replace(/Products\/Name,/g, '');
$("#qUrl").attr("href", url);
Modify the replace call , use regex without quotes
I have my url to switch the contents between 2 languages
http://mydomanin.org/km/components#children-with-disablities
or
http://mydomanin.org/en/components#children-with-disablities
var current_url = document.URL;
var match_url = current_url.replace(/\/km/g,'/en');
console.log(match_url);
I want if find \km will replace by \en and if found \en replaced by \km
How should I do this?
Try this:
var replace = { km:"en", en:"km" };
str = str.replace(/km|en/gi, function(match){
return replace[match];
});
Demo
I would like to extract values from href attribute string using JQuery
$(this).attr("href")
will give me
?sortdir=ASC&sort=Vendor_Name
What i need is these values parsed into an array
myArray['sort']
myArray['sortdir']
Any ideas?
Thanks!
BTW , I saw somewhere else on SO the following similar idea to be used with a query string.
I could not tweak it for my needs just yet.
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Try the following:
var href = $(this).attr("href")
href = href.replace('?', "").split('&');
var myArr = {};
$.each(href, function(i, v){
var s = v.split('=');
myArr[s[0]] = s[1];
});
DEMO
Try this
function getURLParameter(name, string) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(string)||[,null])[1]
);
}
var string = $(this).attr("href");
alert(getURLParameter("sort",string));
Demo here http://jsfiddle.net/jbHa6/ You can change the var string value and play around.
EDIT
Removed the second example, since that code is not that good and does not serve the purpose.
Perhaps is there a better solution but to be quick I should have do something like that
var url = $(this).attr("href");
url = url.replace("?sortdir=", "");
url = url.replace("sort=", "");
myArray['sort'] = url.split("&")[1]; // Or use a temporary tab for your split
myArray['sortdir'] = url.split("&")[0];
That solution depends if your url is still like ?sortdir=ASC&sort=Vendor_Name
You could use jQuery BBQ's deparam function from here:
http://benalman.com/code/projects/jquery-bbq/examples/deparam/
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