Getting All Values from Comma Separated String in Javascript - javascript

I have 1 String Variable in JavaScript which contains 3 Comma separated values shown below:
var session = "mick#yahoo.com,123456,f_id=8";
I want to get all above 3 comma separated values in 3 different variables. What I have achieved so far is getting last comma separated value in elem2 variable and getting other 2 comma separated values 1st and 2nd one in elem1 variable.
var elem1 = session.split(",");
var elem2 = elem1.pop();
document.write("elem1 = "+elem1+"<br/>elem2 = "+elem2);
So my program is not working fine as I wants, please I need quick working solution so that I have another variable elem3 and I will get following output in my browser:
elem1 = mick#yahoo.com
elem2 = 123456
elem3 = f_id=8

You could try the following:
// Initially, we split are comma separated string value on commas.
// In the values an array of these values is stored.
var values = session.split(",");
// Then we get each value based on it's position in the array.
var email = values[0];
var number = values[1];
var id = values[2];
As a side note, I would suggest you use meaningful names for your variables like above. The names elem1, elem2 and elem3 are a bit vague and in future thses namings may obscure even you, let alone another reader of your code.

You can also store the session data in a JavaScript Object. Below iterates through each split string and adds it to an Object.
var myData = {};
// ...
for(var i = 0, x = session.split(","); i < x.length; i++) {
switch(i) {
case 0: myData.email = x[i]; break;
case 1: myData.number = x[i]; break;
case 2: myData.f_id = x[i]; break;
}
}
If you're dealing with multiple data values, it's best to make an array of objects, like so.
var myData = [];
// ...
myData.push({
email: x[0],
number: x[1],
f_id: x[2]
});
And so on. This is a form of JSON Notation. The output would look like this:
[
{
email: "mick#yahoo.com",
number: "123456",
f_id: "f_id=8"
},
{
// Another session, etc.
}
]

You could also use string.replace with a callback as parameter. Very flexible!
Check this for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
For your usecase you may end up with:
function writeParts(match, email, number, id, offset, string) {
document.write("email = "+email+"<br/>number = "+number);
}
// match not-comma followed by a comma (three times)
session.replace(/([^,]+),([^,]+),([^,]+)/, writeParts);

Related

conditional splitting of string and word by matching characters in js

I have very long string that contains html as a string , numbers , my special bindings and numbers I want to split my bindings and sentences with spaces separately but my program is separately my bindings and words .
my js code:-
var x = 'hey this is {{name}} and I love to {{write}} and to learn as
much as I can. Now I am trying to separate sentences and my bindings'
var c = x.match(/\s*\S*\s*/g) // this splits words from string including
space
var mt = x.match(/{(.*)}/g); // trying to take out bindings but this don't
work
mt.forEach(function(a){ // taking each bindings separately
var z = x.match(a)
})
console.log(mt)
Somthing like this .. but I know this is totally wrong please help me
I don't have any idea :-
output that I am expecting:-
(5) ["hey this is", "i", "{{name}}", " and I love to ", "{{write}}", " and to learn as ↵ much as I can. Now I am trying to separate sentences and my bindings"]
How can i do this?
Please don't use jquery
Try this:
I've commented my code hoping it would make it easier to read. But do note that this code is far from perfect although it solves your problem.
var rawString = 'hey this is {{name}} and I love to {{write}} and to learn as much as I can. Now I am trying to separate sentences and my bindings';
var arrayRawString = rawString.match(/\s*\S*\s*/g); // this splits words from string including space
var arrayPlaceholder = rawString.match(/{(.\S*)}+/g); // trying to take out bindings but this don't work
// to store the final output
var separedArray = [];
// keeping track of the index to stich the array up
var posStart = 0;
var posEnd = 0;
arrayPlaceholder.forEach(function(arg){ // taking each bindings separately
// length of the array that holds placeholder (bindings)
var arsLength = arrayRawString.length;
for(var i = 0; i < arsLength; ++i) {
// if the provided text matches the original array's element
if(arrayRawString[i].match(arg)){
// to store the index
posEnd = arrayRawString.indexOf(arrayRawString[i]);
// join the pieces together upto the index defined
var res = arrayRawString.slice(posStart, posEnd).join('');
// to indicate whether the stored string is the placeholder
var flag = true;
// store the string obtained
separedArray.push(res.replace(arrayPlaceholder[(arrayPlaceholder.indexOf(arg) - 1) < 0 ? 0 : arrayPlaceholder.indexOf(arg) - 1 ], ''));
// check if the string still has placeholder (bindings)
// to remove it
for(var j = 0; j < arg.length; ++j) {
if(res[j] !== arg[j]) {
flag = !flag;
}
}
if ( flag ) {
separedArray.push(arg);
}
// last end position is the start position for next round
posStart = posEnd;
// because the loop runs only arrayPlaceholder.length times
// it solves the problem of last part not getting pushed to the final array
if( arrayPlaceholder[arrayPlaceholder.length-1] === arg ) {
res = arrayRawString.slice(posStart, arrayRawString.length).join('');
separedArray.push(res.replace(arg, ''));
}
}
}
});
console.log(separedArray);

How to remove all characters before specific character in array data

I have a comma-separated string being pulled into my application from a web service, which lists a user's roles. What I need to do with this string is turn it into an array, so I can then process it for my end result. I've successfully converted the string to an array with jQuery, which is goal #1. Goal #2, which I don't know how to do, is take the newly created array, and remove all characters before any array item that contains '/', including '/'.
I created a simple work-in-progress JSFiddle: https://jsfiddle.net/2Lfo4966/
The string I receive is the following:
ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC
ABCD/ in the string above can change, and may be XYZ, MNO, etc.
To convert to an array, I've done the following:
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
Using console.log, I get the following result:
["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"]
I'm now at the point where I need the code to look at each index of array, and if / exists, remove all characters before / including /.
I've searched for a solution, but the JS solutions I've found are for removing characters after a particular character, and are not quite what I need to get this done.
You can use a single for loop to go through the array, then split() the values by / and retrieve the last value of that resulting array using pop(). Try this:
for (var i = 0; i < currentUserRole.length; i++) {
var data = currentUserRole[i].split('/');
currentUserRole[i] = data.pop();
}
Example fiddle
The benefit of using pop() over an explicit index, eg [1], is that this code won't break if there are no or multiple slashes within the string.
You could go one step further and make this more succinct by using map():
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',').map(function(user) {
return user.split('/').pop();
});
console.log(currentUserRole);
You can loop through the array and perform this string replace:
currentUserRole.forEach(function (role) {
role = role.replace(/(.*\/)/g, '');
});
$(document).ready(function(){
var A=['ABCD','ABCD/Admin','ABCD/DataManagement','ABCD/XYZTeam','ABCD/DriverUsers','ABCD/RISC'];
$.each(A,function(i,v){
if(v.indexOf('/')){
var e=v.split('/');
A[i]=e[e.length-1];
}
})
console.log(A);
});
You could replace the unwanted parts.
var array = ["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"];
array = array.map(function (a) {
return a.replace(/^.*\//, '');
});
console.log(array);
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(i=0;i<currentUserRole.length;i++ ){
result = currentUserRole[i].split('/');
if(result[1]){
console.log(result[1]+'-'+i);
}
else{
console.log(result[0]+'-'+i);
}
}
In console, you will get required result and array index
I would do like this;
var iur = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC',
arr = iur.split(",").map(s => s.split("/").pop());
console.log(arr);
You can use the split method as you all ready know string split method and then use the pop method that will remove the last index of the array and return the value remove pop method
var importUserRole = ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++;){
var data = currentUserRole[x].split('/');
currentUserRole[x] = data.pop();
}
Here is a long way
You can iterate the array as you have done then check if includes the caracter '/' you will take the indexOf and substact the string after the '/'
substring method in javaScript
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++){
if(currentUserRole[x].includes('/')){
var lastIndex = currentUserRole[x].indexOf('/');
currentUserRole[x] = currentUserRole[x].substr(lastIndex+1);
}
}

Get multiple values from hash in URL

www.domain.com/lookbook.html#look0&product1
On page load I would like to grab the whole hash ie. #look0&product1
then split it up and save the number of the look ie 0 in a variable called var look and the number of the product ie 1 in another variable called var product. Not sure how to achieve this.
Is this also the best way of passing and retrieving such parameters? Thanks
Use var myHash = location.hash to get hash part of URL. Than do var params = myHash.split('&') and after that for each part do part.split('=') to get key-value pairs.
Maybe it's better to pass these parameters via GET from PHP side and than post them inside page when page is processed via PHP?
<input type="hidden" name="look" value="<?php echo isset($_GET['look']) ? $_GET['look'] : '';?>"/>
Here's the pure Javascript method:
function parseHash(hash) {
// Remove the first character (i.e. the prepended "#").
hash = hash.substring(1, hash.length);
// This is where we will store our properties and values.
var hashObj = {};
// Split on the delimiter "&" and for each key/val pair...
hash.split('&').forEach(function(q) {
// Get the property by splitting on all numbers and taking the first entry.
var prop = q.split(/\d/)[0];
// Get the numerical value by splitting on all non-numbers and taking the last entry.
var val_raw = q.split(/[^\d]/);
var val = val_raw[val_raw.length - 1]
// If the property and key are defined, add the key/val pair to our final object.
if (typeof prop !== 'undefined' && typeof val !== 'undefined') {
hashObj[prop] = +val;
}
});
return hashObj;
}
Use like:
parseHash(window.location.hash /* #book10&id1483 */)
/* returns: Object {book: 10, id: 1483} */
I suggest using the norm for passing values through the location's hash: prop=value. Ex: #book=10&id=311. Then you can easily split on = for each property.
You can use .match(re) method with use of regular expression to extract the number from the given string.
You can try this:
var hashes = location.hash.split('&'); // get the hash and split it to make array
var values = hashes.map(function(hash){ // use .map to iterate and get a new array
return hash.match(/\d+/)[0]; // returns the numbers from the string.
});
var loc = "look0345345345&product1";
var hashes = loc.split('&');
var values = hashes.map(function(hash){ return hash.match(/\d+/)[0]; });
document.body.innerHTML = '<pre>'+ JSON.stringify(values) + '</pre>';
You could try this:
var url = 'www.domain.com/lookbook.html#look0&product1'
, result = {}
, expr = RegExp(/[#&]([a-zA-z]+)(\d+)/g);
var parts = expr.exec(url);
while(parts != null && parts.length == 3) {
result[parts[1]] = parts[2];
parts = expr.exec(url);
}
var look = result['look']
, product = result['product'];
document.getElementById('result').innerHTML = 'look = ' + look + '<br>' + 'product = ' + product;
<p id='result'></p>
We are basically using a regular expression to divide the parameter name and value into two groups that we can then get by calling expr.exec(url).
Each time we call expr.exec(url), we get the next set of name and value groups.
We set the value of the parameter to its name in the result object.
In the regular expression /[#&]([a-zA-z]+)(\d+)/g, the g after the /.../ means match each time find the two groups.
The two groups are prefaced by either & or # ([#&]). The first group is a String of letters ([a-zA-z]+), the name of the parameter. The second is a String of numbers (\d+), the value you are looking for.
The regex returns the String that matches the pattern as the first result in the parts array, followed by the groups matched, which which means that our two groups in each iteration will be parts[1] and parts[2].
you should use:
function parseHash(hash){
hash = hash.substring(1, hash.length); //remove first character (#)
var obj ={}; //create the output
var qa = hash.split('&'); //split all parameters in an array
for(var i = 0; i < qa.length; i++){
var fra1 = qa[i].split('='); //split every parameter into [parameter, value]
var prop = fra1[0];
var value = fra1[1];
if(/[0-9]/.test(value) && !isNaN(value)){ //check if is a number
value = parseInt(value);
}
obj[prop] = value; //add the parameter to the value
}
return obj;
}
document.querySelector("input.hash").onkeyup = function(){
console.log( parseHash(document.querySelector("input.hash").value));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="hash"/>
<p class="output"></p>
use as
parseHash(location.hash /* #look=0&product=1 );
/returns {look: 0, product: 1}/

How to get string in regular expression with space

This is my input as string
'controls: ["aa.bb.cc","dd.ee.ff"],elements: []'
I want to get the result of the data in the controls meaning :
"aa.bb.cc","dd.ee.ff"
I tried pattern
/.*(controls:.*).*/
but I didn't get all the result
I think my problem is becuase the new line
You can do it with regEx
var c = 'controls: ["aa.bb.cc", "dd.ee.ff"], elements: []';
var match = c.match(/("[a-z.]+")/g);
// or c.match(/([a-z][a-z][.][a-z][a-z][.][a-z][a-z])/);
// to strictly match letters . letters . letters
// or for a shorter match: c.match(/(\w+[.]\w+[.]\w+)/);
console.log(match); // an array of your values
EDIT:
if you only want to get the values in controls and not element, you can get the controls values out with the regEx /controls: ([\["a-z., \]]+,)/g
You could simply parse your input as a JSON object then loop throught the controls array:
var input='controls: ["aa.bb.cc", "dd.ee.ff"],
elements: []';
json = JSON.parse(input);
var controls=json.controls;
//then loop throught the controls values
for(var i=0;i<controls.length;i++){
console.log(controls[i]);
}
I think that should do it.
This might look like a very crude solution, but it works.
This expression will give you aa.bb.cc :
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[1]
and this will give the next element i.e. dd.ee.ff
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/)[2]
In general,
var str = "controls: [\"aa.bb.cc\",\"dd.ee.ff\"],elements: []";
var resLength = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/).length;
var res = str.match(/controls: \[(.*)\]/)[1].match(/\"(.*)\",\"(.*)\"/);
for (var i=1; i<resLength; i++) {
console.log(res[i]);
}

Split function going Abnormal in JavaScript

This is the Contents of file from where i am reading...
aaa 3333,bbb 5,ccc 10
I am getting un defined for the keyvalue[2], [3], [4] and [5]. Why is it so???
I am actually first spliting based on , and then based on space.
because you split by comma first, so item is now 'PrimeSuiteId 3333'. When you split that by space you get two items only, so 3rd value (keyvalue[2]) and above is empty.
Edit: possible fix to make second part of your script work
swap
var items = contents.toString().split(',');
with
var items = contents.toString().replace(/,/,' ');
which will simply replace commas with spaces in the original string so your array of expected values matches up
Another edit: because splitting by comma or space is better (as in comments)
var contents = f.read();
Ti.API.info(contents);
var items = contents.toString(); // changed to return complete string not split
// removed for loop altogether
var keyvalue = items.split(/,|\s/); // changed to split by comma or space
var AppointmentSearchDaysAfter = keyvalue[0];
var AppointmentSearchDaysAfterValue = keyvalue[1];
var AppointmentSearchDaysBefore = keyvalue[2];
var AppointmentSearchDaysBeforeValue = keyvalue[3];
var PrimeSuiteId = keyvalue[4];
var PrimeSuiteIdValue = keyvalue[5];
From the contents in the contents file you should only be able to get values for
var AppointmentSearchDaysAfter = keyvalue[0];
var AppointmentSearchDaysAfterValue = keyvalue[1];
You only have one space for each data entry between the commas
Split function is working fine, you are expecting it to behave abnormal.
You will get only two values in array after split by space. From where will it bring 6 values!!!?
The rest values you will get in next iterations.
Instead of declaring individual variables for each item and then loading them from the contents string, you can reduce the whole thing to an object with key/value pairs:
var items = contents.split(',').reduce(function (acc, val) {
var split = val.split(' ');
return acc[split[0]] = split[1], acc;
}, {});
To test what the values are, try:
console.log(items.PrimeSuiteId); // outputs 3333
console.log(items.AppointmentSearchDaysBefore); // outputs 5
console.log(items.AppointmentSearchDaysAfter); // outputs 10

Categories

Resources