Extract values from href attribute string using JQuery - javascript

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/

Related

Need to Replace by JavaScript

Need to Replace by jquery.
MY Json is:
var money={"money1":"957.06","money2":"1,368,737.85"}
Need to get result:
var money={"money1":"957.06","money2":"1368737.85"}
var res = money.replace(/,/, "");
by this its replaceing all the ","how to slove this?
You first need to iterate thru every value and then replace in it:
var money={"money1":"957.06","money2":"1368737.85"}
$.each( money, function( key, value ) {
value = value .replace(/,/, "");
});
use JavaScript replace()
e.g.:
money.money2 = money.money2.replace(/,/g, "");
http://www.w3schools.com/jsref/jsref_replace.asp
Add a g (global) flag to your regex; otherwise, only the first match will be replaced. Also, you need to access the actual properties of money that contain values:
money.money1 = normalizeMoney(money.money1);
money.money2 = normalizeMoney(money.money2);
function normalizeMoney(str) {
return str.replace(/,/g, '');
}
Just with JavaScript (without jQuery):
var money={"money1":"957.06","money2":"1,368,737.85"};
Object.keys(money).map(function(value, index) {
money[value] = money[value].replace(/,/g, '');
});
console.log(money);
// Object {money1: "957.06", money2: "1368737.85"}

Regex not working to remove string/whatever

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

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

find and replace by using js or jquery

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

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

Categories

Resources