Split URL string to get each parameter value in javascript [duplicate] - javascript

This question already has answers here:
How to convert URL parameters to a JavaScript object? [duplicate]
(34 answers)
Closed 8 years ago.
var url = "journey?reference=123line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC"
How can I split the string above so that I get each parameter's value??

You could use the split function to extract the parameter pairs. First trim the stuff before and including the ?, then split the & and after that loop though that and split the =.
var url = "journey?reference=123line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC";
var queryparams = url.split('?')[1];
var params = queryparams.split('&');
var pair = null,
data = [];
params.forEach(function(d) {
pair = d.split('=');
data.push({key: pair[0], value: pair[1]});
});
See jsfiddle

Try this:
var myurl = "journey?reference=123&line=A&destination=China&operator=Belbo&departure=1043&vehicle=ARC";
var keyval = myurl.split('?')[1].split('&');
for(var x=0,y=keyval.length; x<y; x+=1)
console.log(keyval[x], keyval[x].split('=')[0], keyval[x].split('=')[1]);

to split line in JS u should use:
var location = location.href.split('&');

Related

How to create a function to split the following string? [duplicate]

This question already has answers here:
What is the shortest function for reading a cookie by name in JavaScript?
(20 answers)
Closed 2 years ago.
I have this string
"G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;
_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5"
And i need some sort of function to split this string given an argument , for example given that my string is text
text.split(";") , will split it into an array separating it by ";"
But i need a function like this
returnText(text , property) that would work like
returnText(text, "_gcl_au") --> returns "someglcau"
You could actually use a regex replacement approach here, for a one-liner option:
function returnText(text, property) {
var term = text.replace(new RegExp("^.*\\b" + property + "=([^;]+)\\b.*$", "gm"), "$1");
return term;
}
var input = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie;_ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(input, "_gcl_au"));
you can use split, just as you tried:
function returnText(text , property){
entries = text.split('; ');
const newEntries = [];
entries.forEach(item => {
let vals = item.split('=');
newEntries[vals[0]] = vals[1]
});
return newEntries[property];
}
const text = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(text,'_gcl_au'));

SubString in JavaScript [duplicate]

This question already has answers here:
How to get the nth occurrence in a string?
(14 answers)
Closed 2 years ago.
For example, I have a string like following
var string = "test1;test2;test3;test4;test5";
I want the following substring from the above string, I don't know the startIndex, the only thing I can tell substring should start after the second semicolon to till the end.
var substring = "test3;test4;test5";
Now I want to have substring like following
var substring2 = "test4;test5"
How to achieve this in JavaScript
You mean this?
const string = "test1;test2;test3;test4;test5";
const arr = string.split(";")
console.log(arr.slice(2).join(";")); // from item #2
console.log(arr.slice(-2).join(";")) // last 2 items
If the string is very long, you may want to use one of these versions
How to get the nth occurrence in a string?
As a function
const string = "test1;test2;test3;test4;test5";
const restOfString = (string,pos) => {
const arr = string.split(";")
return arr.slice(pos).join(";"); // from item #pos
};
console.log(restOfString(string,2))
console.log(restOfString(string,3))
Try to use a combination of string split and join to achieve this.
var s = "test1;test2;test3;test4;test5";
var a = s.split(";")
console.log(a.slice(3).join(";"))

Check whether an array includes a string but ignore rest other letters in that string [duplicate]

This question already has answers here:
Is there a javascript method to find substring in an array of strings?
(5 answers)
How to check if a string contains text from an array of substrings in JavaScript?
(24 answers)
Closed 4 years ago.
I have a variable like,
var url = "/login/user";
And I have an array like,
var x = ["login", "resetpassword", "authenticate"];
Now I need to check, whether that url string is present in an array of string. As we can see that login is present in an array but when i do x.indexOf(url), it always receive false because the field url has rest other letters also. So now how can I ingnore those letters while checking a string in an array and return true?
Use .some over the array instead:
var url = "/login/user";
var x = ["login", "resetpassword", "authenticate"];
if (x.some(str => url.includes(str))) {
console.log('something in X is included in URL');
}
Or, if the substring you're looking for is always between the first two slashes in the url variable, then extract that substring first, and use .includes:
var url = "/login/user";
var x = ["login", "resetpassword", "authenticate"];
var foundStr = url.split('/')[1];
if (x.includes(foundStr)) {
console.log('something in X is included in URL');
}
One way is to split url with / character and than use some
var url = "/login/user";
var x = ["login", "resetpassword", "authenticate"];
let urlSplitted = url.split('/')
let op = urlSplitted.some(e=> x.includes(e))
console.log(op)
You could join the given words with a pipe (as or operator in regex), generate a regular expression and test against the string.
This works as long as you do not have some characters with special meanings.
var url = "/login/user",
x = ["login", "resetpassword", "authenticate"];
console.log(new RegExp(x.join('|')).test(url));

How to parse url to get desired value [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 6 years ago.
How can I parse a link in jqueryjavascript?
I have the url (some path)/restaurantProfile.php?id=51
And I want to parse this to only obtain the 51. (keep in mind this needs to be generalized. The id won't obviously be always 51...)
Thanks in advance!
You can split the string at id=:
var url = 'some/path/restaurantProfile.php?id=51';
var id = url.split('id=')[1]; // 51
I forget where I saw this, but here is a nice jquery function you can use for this:
//jQuery extension below allows for easy query-param lookup
(function($) {
$.QueryString = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'))
})(jQuery);
Usage like so:
var restaurantId = $.QueryString["id"];
You can make use of Regular Expression in javascript. RegExp Object provides methods to Match the Regular Expression with a input String.
You can make use of string object split method to split the string by using a separator character.
There is a similar question at How can I get query string values in JavaScript? for more options.
You can use the URLSearchParams API to work with the query string of a URL
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
// get the current url from the browser
var x = new URLSearchParams(window.location.search);
// get the id query param
var id = x.get('id');

Get image name out of image address with JavaScript [duplicate]

This question already has answers here:
How to pull the file name from a url using javascript/jquery?
(16 answers)
Closed 9 years ago.
I would like to get the image name out of the address.
This is the value I with the JavaScript:
http://localhost:51557/img/column-sortable.png
document.getElementById("ctl00_contentHolder_iSortColumn").value = columnNumber;
alert(imageName);
Whats the best way to get column-sortable.png out of the string?
As long as there's never anything after the image name in the URL (no query string or hash) then the following should work:
var str = "http://localhost:51557/img/column-sortable.png";
alert(str.substring(str.lastIndexOf('/') + 1));
Please refer to the split function:
var url = http://localhost:51557/img/column-sortable.png;
var elementArray = url.split('/');
var imageName = elementArray[elementArray.length - 1];
JSFiddle
If you want to try using Regex, check this out.
var imgURL = "http://localhost:51557/img/column-sortable.png";
var imageName = imgURL.replace( /^.*?([^/]+\..+?)$/, '$1' );
alert(imageName);

Categories

Resources