How to get 2 strings separated by a dash? - javascript

In a project I got IDs consisting of two parts, The parts are separated by a dash. How can I get part 1 and part 2?
JS
var ID = "100-200";
var id_part1 = 0;
var id_part2 = 0;

Try this:
var id = "100-200";
var arr = id.split("-");
alert(arr[0]);
alert(arr[1]);

With simple JavaScript:
ID = "100-200";
var values = ID.split('-');
var id_part1 = values[0];
var id_part2 = values[1];

var id = "100-200";
var array = id.split("-");
var id_part1 = array[0];
var id_part2 = array[1];

Use Split: Try this
var str = "100-200";
var res = str.split("-");
Result is in array list.

You can use :
var ID= "100-200" ;
ID=ID.split('-')[1];
var id_part1 = ID[0];
var id_part2 = ID[1];

Now it can be done in one line with the destructuring assignment:
var ID = "100-200";
var [id_part1, id_part2] = ID.split('-');
console.log('id_part1: ', id_part1);
console.log('id_part2: ', id_part2);

Related

JavaScript splice more than 1 value?

How to splice the string value so the output only become 'LA1','LA4'. I tried the method below but it still gave me string_2 output.
var string_1 = 'LA2,LA3'
var string_2 = "LA1,LA2,LA3,LA4";
var unique_1 = string_1.split(',');
var unique_2 = string_2.split(',');
const index = unique_2.indexOf(unique_1);
if (index > -1) {
unique_2.splice(index, 1);
}
console.log(unique_2);
Instead of using splice() You can filter() with includes().
var string_1 = 'LA2,LA3'
var string_2 = "LA1,LA2,LA3,LA4";
var unique_1 = string_1.split(',');
var unique_2 = string_2.split(',');
var filtered = unique_2.filter(s => !unique_1.includes(s))
console.log(filtered);
If your lists are very large, you might want to use something other than an array with includes() such as a Set that offers constant time lookups.
Array.prototype.indexOf() only finds one element and can not find an array.
To get the expected value, you can do as follows.
var string_1 = 'LA2,LA3'
var string_2 = "LA1,LA2,LA3,LA4";
var unique_1 = string_1.split(',');
var unique_2 = string_2.split(',');
unique_2 = unique_2.filter(item => !unique_1.includes(item));
console.log(unique_2);
using reduce:
var string_1 = 'LA2,LA3'
var string_2 = "LA1,LA2,LA3,LA4";
var unique_1 = string_1.split(',');
var unique_2 = string_2.split(',');
const result = unique_2.reduce((acc, item) => {
!string_1.includes(item) && acc.push(item)
return acc
}, [])
console.log(result)

How to write a For Loop with variables that include an incremental split [] to minify JS code?

Hopefully I am asking this question in the right way, I am a total noob to For Loops in JavaScript...
I have to write a For Loop for this:
var file = '/home/xxxxx/xxxx/xxxx/xxxx';
var obj = result.rows;
var split = JSON.stringify(obj).split(',');
var date1rpl = split[0].replace(/\"/g,"");
var date1og = date1rpl.slice(2,100);
var date1 = splitabc(date1og);
var usr1 = split[1].replace(/\"/g,"");
var session1 = split[2].replace(/("|])/g,"");
var date2rpl = split[3].replace(/\"/g,"");
var date2og = date2rpl.slice(1,100);
var date2 = splitabc(date2og);
var session2 = split[5].replace(/("|])/g,"");
var usr2 = split[4].replace(/\"/g,"");
var date3rpl = split[6].replace(/\"/g,"");
var date3og = date3rpl.slice(1,100);
var date3 = splitabc(date3og);
var session3 = split[8].replace(/("|])/g,"");
var usr3 = split[7].replace(/\"/g,"");
var date4rpl = split[9].replace(/\"/g,"");
var date4og = date4rpl.slice(1,100);
var date4 = splitabc(date4og);
var session4 = split[11].replace(/("|])/g,"");
var usr4 = split[10].replace(/\"/g,"");
var date5rpl = split[12].replace(/\"/g,"");
var date5og = date5rpl.slice(1,100);
var date5 = splitabc(date5og);
var session5 = split[14].replace(/("|])/g,"");
var usr5 = split[13].replace(/\"/g,"");
jsonfile.writeFile(file, obj);
The split[] seems to be incrementing by +3 for each user, session, date1rpl. How can I include this in a for loop that would run through the variables so that I can just have daterpl, dateog, date, usr, and session as variables and not have to number each variable and repeat it?
var date1rpl = split[0].replace(/\"/g,"");
var date1og = date1rpl.slice(2,100);
var date1 = splitabc(date1og);
var usr1 = split[1].replace(/\"/g,"");
var session1 = split[2].replace(/("|])/g,"");
So you want to loop over ever item in the split array and do some work on it and then save the updated version for later use.
You can use a For Loop
var dates = [];
var split = JSON.stringify(obj).split(',');
for(var i = 0; i< split.length; i++){
var dateRpl = split[i].replace(/\"/g,"");
var dateOG = dateRpl.slice(2,100);
dates.push(splitabc(dateOG));
}
// dates is now an array of all the processed dates
Or you can use the forEach method on arrays
var dates = [];
var split = JSON.stringify(obj).split(',');
split.forEach(function(string) {
var dateRpl = string.replace(/\"/g,"");
var dateOG = dateRpl.slice(2,100);
dates.push(splitabc(dateOG));
});
// dates is now an array of all the processed dates

Split an array cause an error: not a function

I want to split an array that already have been split.
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = string.split(',');
var array_s = array_dt.split('|');
console.log(array_s);
That code returns TypeError: array_dt.split is not a function.
I'm guessing that split() can not split an array. Have I wrong?
Here's how I want it to look like. For array_dt: 2016-08-08,2016-08-07,2016-08-06,2016-08-05,2016-08-04. For array_s: 63,67,64,53,63. I will use both variables to a chart (line) so I can print out the dates for the numbers. My code is just as example!
How can I accomplish this?
Demo
If you want to split on both characters, just use a regular expression
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = string.split(/[,|]/);
console.log(array_dt)
This will give you an array with alternating values, if you wanted to split it up you can do
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = string.split(/[,|]/);
var array1 = array_dt.filter( (x,i) => (i%2===0));
var array2 = array_dt.filter( (x,i) => (i%2!==0));
console.log(array1, array2)
Or if you want to do everything in one go, you could reduce the values to an object
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array = string.split(/[,|]/).reduce(function(a,b,i) {
return a[i%2===0 ? 'dates' : 'numbers'].push(b), a;
}, {numbers:[], dates:[]});
console.log(array)
If performance is important, you'd revert to old-school loops, and two arrays
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array = string.split(/[,|]/);
var array1 = [];
var array2 = [];
for (var i = array.length; i--;) {
if (i % 2 === 0) {
array1.push(array[i]);
} else {
array2.push(array[i]);
}
}
console.log(array1, array2)
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = [];
var array_s = [];
string.split('|').forEach(function(el){
var temp = el.split(",");
array_dt.push(temp[0]);
array_s.push(temp[1]);
});
console.log(array_dt);
console.log(array_s);
Just do it one step at a time - split by pipes first, leaving you with items that look like 2016-08-08,63. Then for each one of those, split by comma, and insert the values into your two output arrays.
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var arr = string.split("|");
var array_dt = [];
var array_s = [];
arr.forEach(function(item) {
var x = item.split(",");
array_dt.push(x[0]);
array_s.push(x[1]);
});

Transform simple string in a key: value array

I've the following string in the JavaScript:
test: hi,
otherTest: hiAgain
How can I transform in a key: value array?
var string = 'test: hi,otherTest: hiAgain';
var sets = string.split(","); //splits string by commas
var out = new Array(); //prepare the output array
for (var i=0; i<sets.length; i++) {
var keyval = sets[i].split(":"); //split by colon for key/val
out[keyval[0]] = keyval[1].trim(); //trim off white spaces and set array
}
Here is a quick example:
var str='test: hi,\notherTest: hiAgain';
var obj={};
var kvp=str.split('\n');
for(k=0;k<kvp.length;k++){
var temp=kvp[k].split(' ');
obj[temp[0]]=temp[1];
}
console.log(JSON.stringify(obj));
Here you are:
var data = ['test: hi', 'otherTest: hiAgain'];
var result = [];
$.each(data, function(index, value){
var keyValue = value.split(':');
var obj = {};
obj[keyValue[0].trim()] = keyValue[1].trim();
result.push(obj);
});
alert(JSON.stringify(result));
Hope this help.

How to parse bracket tag on Javascript

I have tag like this, how the best way to get every key and value of those attribute and populate it within an array (number of attribute will be increasing)?
myData = '[data attr1="value1" attr2="value2" attr3="value3"]';
and get result array :
var arr = new Array();
arr['attr1'] = "value1";
arr['attr2'] = "value2";
arr['attr3'] = "value3";
and so on...
This probably does what you want, though it assumes that tag is already in the format you have described, i.e. a singular occurrence of [data ... ].
Also, the regular expression is purely based on what I've seen in your question; not sure whether it will break on other strings.
function decode(tag)
{
var r = /(\w+)="([^"]*)"/g,
h = {};
while ((m = r.exec(tag)) !== null) {
h[m[1]] = m[2];
}
return h;
}
Since you have string key in the data, use jquery object instead of array.
var arr = {};
var str = '[data attr1="value1" attr2="value2" attr3="value3"]​​​';
var n = str.split('[data ');
var str_arr = n[1].replace(']','').split(" ");
jQuery.each(str_arr,function(val){
var x = str_arr[val].split('=');
arr[x[0]] = x[1].replace('"','').slice(0,-1);
});
console.log(arr);
Try this code. It may help you.
Here is the DEMO
Though it can be more optimized if you put some more details about your code.
var tagRe = /\[(\w+)((?:\s+\w+="[^"]{0,50}")*)\s*]/g;
var attrRe = /\b(\w+)="([^"]*)"/g;
function parse(text) {
var result = [];
tagRe.lastIndex = 0; // reset start position
var tagMatch = tagRe.exec(text);
while (tagMatch) {
var currentTag = { 'name': tagMatch[1], 'attrs': {} };
var attrString = tagMatch[2];
attrRe.lastIndex = 0;
var attrMatch = attrRe.exec(attrString);
while (attrMatch) {
var attrName = attrMatch[1];
var attrValue = attrMatch[2];
currentTag.attrs[attrName] = attrValue;
attrMatch = attrRe.exec(attrString); // next match
}
result.push(currentTag);
tagMatch = tagRe.exec(text);
}
return result;
}
parse('[data attr1="value1" attr2="value2" attr3="value3"]');
> [{name:'data',attrs:{attr1:'value1',attr2:'value2',attr3:'value3'}}]
This works for any number of tags in the string. The name of the tag does not matter.

Categories

Resources