Javascript string manipulation url - javascript

My problem is I am trying to extract certain things from the url. I am currently using
window.location.href.substr()
to grab something like "/localhost:123/list/chart=2/view=1"
What i have now, is using the index positioning to grab the chart and view value.
var chart = window.location.href.substr(-8);
var view = window.location.href.substr(-1);
But the problem comes in with I have 10 or more charts. The positioning is messed up. Is there a way where you can ask the code to get the string between "chart=" and the closest "/"?

var str = "/localhost:123/list/chart=2/view=1";
var data = str.match(/\/chart=([0-9]+)\/view=([0-9]+)/);
var chart = data[1];
var view = data[2];
Of course you may want to add in some validation checks before using the outcome of the match.
Inspired by Paul S. I have written a function version of my answer:
function getPathVal(name)
{
var path = window.location.pathname;
var regx = new RegExp('(?:/|&|\\?)'+name+'='+'([^/&,]+)');
var data = path.match(regx);
return data[1] || null;
}
getPathVal('chart');//2
Function should work for fetching params from standard get parameter syntax in a URI, or the syntax in your example URI

Here's a way using String.prototype.indexOf
function getPathVar(key) {
var str = window.location.pathname,
i = str.indexOf('/' + key + '=') + key.length + 2,
j = str.indexOf('/', i);
if (i === key.length + 1) return '';
return str.slice(i, j);
}
// assuming current path as described in question
getPathVar('chart');

You could split your string up, with "/" as delimiter and then loop through the resulting array to find the desired parameters. That way you can easily extract all parameters automatically:
var x = "/localhost:123/list/chart=2/view=1";
var res = {};
var spl = x.split("/");
for (var i = 0; i < spl.length; i++) {
var part = spl[i];
var index = part.indexOf("=");
if (index > 0) {
res[part.substring(0, index)] = part.substring(index + 1);
}
}
console.log(res);
// res = { chart: 2, view: 1}
FIDDLE

Related

How to split and change to different format in javascript

I am new for javascript, I have a one long string i want to split after 3rd commas and change diffferent format. If you are not understand my issues. Please see below example
My string:
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
I want output like this:(Each item should be in next line)
Idly(3 Pcs) - 10 = 200
Ghee Podi Idly - 10 = 300
How to change like this using JavaScript?
Just copy and paste it. Function is more dynamic.
Example Data
var testData = "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
Function
function writeData(data){
data = data.split(',');
var tempLine='';
for(var i=0; i<data.length/3; i++) {
tempLine += data[i*3+1] + ' - ' + data[i*3] + ' = ' + data[i*3+2] + '\n';
}
alert(tempLine);
return tempLine;
}
Usage
writeData(testData);
Use split method to transform the string in a array and chunk from lodash or underscore to separate the array in parts of 3.
// A custom chunk method from here -> http://stackoverflow.com/questions/8495687/split-array-into-chunks
Object.defineProperty(Array.prototype, 'chunk_inefficient', {
value: function(chunkSize) {
var array=this;
return [].concat.apply([],
array.map(function(elem,i) {
return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
})
);
}
});
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var arr = test.split(',');
var arr = arr.chunk_inefficient(3);
arr.forEach(function (item) {
console.log(item[1]+' - '+item[0]+' = '+item[2]);
});
You can use split to split the string on every comma. The next step is to iterate over the elements, put the current element into a buffer and flush the buffer if it's size is three. So it's something like:
var tokens = test.split(",");
var buffer = [];
for (var i = 0; i < tokens.length; i++) {
buffer.push(tokens[i]);
if (buffer.length==3) {
// process buffer here
buffer = [];
}
}
If you have fix this string you can use it otherwise validate string.
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var test2= test.split(",");
var temp_Str= test2[1]+' - '+test2[0]+' = '+test2[2]+'\n';
temp_Str+= test2[4]+'-'+test2[3]+' = '+test2[5];
alert(temp_Str);

Javascript pull data from string?

I have a long URL that contains some data that I need to pull. I am able to get the end of the URL by doing this:
var data = window.location.hash;
When I do alert(data); I receive a long string like this:
#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600
note in the example the access token is not valid, just random numbers I input for example purpose
Now that I have that long string stored in a variable, how can I parse out just the access token value, so everything in between the first '=' and '&. So this is what I need out of the string:
0u2389ruq892hqjru3h289r3u892ru3892r32235423
I was reading up on php explode, and others java script specific stuff like strip but couldn't get them to function as needed. Thanks guys.
DEMO (look in your debug console)
You will want to split the string by the token '&' first to get your key/value pairs:
var kvpairs = document.location.hash.substring(1).split('&');
Then, you will want to split each kvpair into a key and a value:
for (var i = 0; i < kvpairs.length; i++) {
var kvpair = kvpairs[i].split('=');
var k = kvpair[0];
var v = kvpair[1];
if (k != 'access_token')
continue;
console.log(v); //Here's your access token.
}
Here is a version wrapped into a function that you can use easily:
function getParam(hash, key) {
var kvpairs = hash.substring(1).split('&');
for (var i = 0; i < kvpairs.length; i++) {
var kvpair = kvpairs[i].split('=');
var k = kvpair[0];
var v = kvpair[1];
if (k != key)
continue;
return v;
}
return null;
}
Usage:
getParam(document.location.hash, 'access_token');
data.split("&")[0].split("=")[1]
var str = "#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600";
var requiredValue = str.split('&')[0].split('=')[1];
I'd use regex in case value=key pair changes position
var data = "#token_type=Bearer&access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&expires_in=3600";
RegExp("access_token=([A-Za-z0-9]*)&").exec(data)[1];
output
"0u2389ruq892hqjru3h289r3u892ru3892r32235423"
Looks like I'm a bit late on this. Here's my attempt at a version that parses URL parameters into a map and gets any param by name.
var str = "#access_token=0u2389ruq892hqjru3h289r3u892ru3892r32235423&token_type=Bearer&expires_in=3600";
function urlToMap(url){
var startIndex = Math.max(url.lastIndexOf("#"), url.lastIndexOf("?"));
url = url.substr(startIndex+1);
var result = {};
url.split("&").forEach(function(pair){
var x = pair.split("=");
result[x[0]]=x[1];
});
return result;
}
function getParam(url, name){
return urlToMap(url)[name];
}
console.log(getParam(str, "access_token"));
To answer to your question directly (what's between this and that), you would need to use indexOf and substring functions.
Here's a little piece of code for you.
function whatsBetween (_strToSearch, _leftText, _rightText) {
var leftPos = _strToSearch.indexOf(_leftText) + _leftText.length;
var rightPos = _strToSearch.indexOf(_rightText, leftPos);
if (leftPos >= 0 && leftPos < rightPos)
return _strToSearch.substring(leftPos, rightPos);
return "";
}
Usage:
alert(whatsBetween, data,"=","#");
That said, I'd rather go with a function like crush's...
try this
var data = window.location.hash;
var d1 = Array();
d1 = data.split("&")
var myFilteredData = Array();
for( var i=0;i<d1.length;i++ )
{
var d2 = d1[i].split("=");
myFilteredData.push(d2[1]); //Taking String after '='
}
I hope it helps you.

How to get the Last Value from Cookie with 2 variables inside Using split() methode in javascript

I have cookie that consist of 2 variables. I want to get the value from the variable #2 (the last one) But I don´t know how to deal with that.
From PHP
I have set cookie like this :
setcookie ('mysite'.$user_id,'user_id='. $user_id. '&msg_id='. $c_id, time() + $cookie_time);
What I'm trying to get is the value of msg_id
In javascript
var ca="mysite"+user_id;
ca = new Array();
ca = document.cookie.split(';');
for (var w in ca)
NmeVal = new Array();
NmeVal = ca[w].split('=');
But how can I get just only the value of msg_id as I mentioned above?
UPDATE
I got it to work now by doing this:
var NmeVal = new Array();
NmeVal = ca[w].split('=');
var vl =unescape(NmeVal[1]);
var gala = vl.split('=');
alert(gala[2]);
I get the only value I want::
it work in IE, FIrefox, Chrome
But why didn´t it work in Safari ?
UPDATE # FINAL
Finally I found the solution jquery.cookie.js
Only 3 lines work and the job is done !!!
Create - get - delete cookie like crazy and the plugin is not that big file like other packages.
And because of this plug in I start to use cookie like crazy now :)
You are better of storing information in cookies this way:
setcookie("user_id", $user_id);
setcookie("msg_id", $c_id);
// ...
Javascript function for getting the cookie value by giving a name:
var user_id = getCookie("user_id");
function getCookie(name) {
var result = "";
var myCookie = " " + document.cookie + ";";
var searchName = " " + name + "=";
var startOfCookie = myCookie.indexOf(searchName);
var endOfCookie;
if (startOfCookie != -1) {
startOfCookie += searchName.length;
endOfCookie = myCookie.indexOf(";", startOfCookie);
result = unescape(myCookie.substring(startOfCookie, endOfCookie));
}
return result;
}
When you are parsing a cookie, parse from the outside in.
One thing I found when parsing the cookie you posted was an additional space before 'mysite'. Using the console and logging the results of each step can help you find small issues like that.
Split first by ','
loop and split by '='
unescape value to the right of the '='
Then in your case, loop and split by '&'
This routine should work for you ([Fiddle][5]):
// Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
function parseCookie(cookie) {
var vals = cookie.split(',');
var nameValue = {}, cur, mysite;
for (var i = 0; i < vals.length; ++i) {
cur = vals[i].split('=');
nameValue[cur[0].trim()] = unescape(cur[1]);
}
mysite = nameValue.mysite.split('&');
nameValue.mysite = {};
for (i = 0; i < mysite.length; ++i) {
cur = mysite[i].split('=');
nameValue.mysite[cur[0].trim()] = cur[1];
}
return nameValue;
}
var cookie = "PHPSESSID=oleGInunYQIP7QSLpDUVR3, mysite=usr%3DChrome%26hash%3D594f803b380a41396ed63dca39503542";
console.log(JSON.stringify(parseCookie(cookie)));
Result:
{"PHPSESSID":"oleGInunYQIP7QSLpDUVR3","mysite":{"usr":"Chrome","hash":"594f803b380a41396ed63dca39503542"}}
You can retrieve any value you need by something like:
var usr = result.mysite.usr;

javascript - Get a portion of the cookie value with substr method

I have a cookie called "login" that contains a structure like "username|hashcode|salt".
Here's my code:
function readTheCookie(the_info)
{
var the_cookie = document.cookie;
var the_cookie = unescape(the_cookie);
var broken_cookie2 = the_cookie.substr(6);
alert(broken_cookie2);
}
readTheCookie('login');
I'ts giving me
pickup22|d47f45d141bf4ecc999ec4c083e28cf7|4ece9bce292e1
Now I just want the first part (everything before the first pipe , in that case, I want pickup22)
How can I do that? Cause the username will never be the same, so I cant put a "fixed" lenght.
Any help appreciated!
var readTheCookie = function (the_info) {
var the_cookie = document.cookie.split(";"), a = the_cookie.length, b;
for (b = 0; b < a; b += 1) {
if (the_cookie[b].substr(0, the_info.length) === the_info) {
return the_cookie.split("=")[1].split("|")[0];
}
}
if (b === a) {
return "";
}
},
username = readTheCookie('login');
That is nice and compact, plus easy to read, and finally it is JSLint compliant. Enjoy!
best way is to use split() method.
var parts = new Array();
parts = broken_cookie2.split("|");
var username = parts[0];
var hashcode = parts[1];
var salt = parts[2];

Transform a string into array using javascript

I have a string like this:
string = "locations[0][street]=street&locations[0][street_no]=
34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
What must I do with this string so i can play with locations[][] as I wish?
You could write a parser:
var myStr = "locations[0][street]=street&locations[0][street_no]=34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
function parseArray(str) {
var arr = new Array();
var tmp = myStr.split('&');
var lastIdx;
for (var i = 0; i < tmp.length; i++) {
var parts = tmp[i].split('=');
var m = parts[0].match(/\[[\w]+\]/g);
var idx = m[0].substring(1, m[0].length - 1);
var key = m[1].substring(1, m[1].length - 1);
if (lastIdx != idx) {
lastIdx = idx;
arr.push({});
}
arr[idx * 1][key] = parts[1];
}
return arr;
}
var myArr = parseArray(myStr);
As Shadow wizard said, using split and eval seems to be the solution.
You need to initialize locations first, if you want to avoid an error.
stringArray=string.split("&");
for (var i=0;i<stringArray.length;i++){
eval(stringArray[i]);
}
However, you might need to pay attention to what street and street_no are.
As is, it will produce an error because street is not defined.
Edit: and you'll need to fully initialize locations with as many item as you'll have to avoid an error.

Categories