String Split for only first time - javascript

I want to split the below input string as output string.
Input = 'ABC1:ABC2:ABC3:ABC4'
Output = ['ABC1','ABC2:ABC3:ABC4']
let a = 'ABC1:ABC2:ABC3:ABC4'
a.split(':', 2); // not working returning ['ABC1','ABC2']

You can use this, works in all browsers
var nString = 'ABC1:ABC2:ABC3:ABC4';
var result = nString.split(/:(.+)/).slice(0,-1);
console.log(result);

let a = 'ABC1:ABC2:ABC3:ABC4'
const head = a.split(':', 1);
const tail = a.split(':').splice(1);
const result = head.concat(tail.join(':'));
console.log(result); // ==> ["ABC1", "ABC2:ABC3:ABC4"]
Example: https://jsfiddle.net/4nq1tLye/

You can use indexOf and slice:
var a = 'ABC1:ABC2:ABC3:ABC4';
var indexToSplit = a.indexOf(':');
var first = a.slice(0, indexToSplit);
var second = a.slice(indexToSplit + 1);
console.log(first);
console.log(second);

console.log('ABC1:ABC2:ABC3:ABC4'.replace(':','#').split('#'));

Related

Combine array in JavaScript with underscore character

Var a = "837297,870895"
Var b = "37297,36664"
OutPut = "837297_37297,870895_36664
I tried multiple script but does not working
You can split and map the splitted array as such:
var a = "837297,870895"
var b = "37297,36664"
var output = a.split(',').map((e,i)=> e+"_"+b.split(',')[i])
console.log(output.toString())
For ES2015 or lower
var a = "837297,870895"
var b = "37297,36664"
var output = a.split(',').map(function(e,i){return e+"_"+b.split(',')[i]})
console.log(output.toString())
You can start by converting the two strings (lists) into arrays using .map() and .split() methods.
Then use .map() and .join() methods to produce the desired string (list):
const a = "837297,870895";
const b = "37297,36664";
const [c,d] = [a,b].map(e => e.split(','));
const output = c.map((e,i) => `${e}_${d[i]}`).join();
console.log( output );

Javascript string to special array

I have a string:
var string = "test,test2";
That I turn into an array:
var array = string.split(",");
Then I wrap that array into a larger array:
var paragraphs = [array];
Which outputs:
[['test','test2']]
But I need it to output:
[['test'],['test2']]
Any clue how I can do this?
Just map each item into an array containing that item:
var string = "test,test2";
var result = string.split(",").map(x => [x]);
// ^--------------
console.log(result);
let test_string = "test,test2";
let result = test_string.split(',').map(item => [item])
console.log(result)
You can get expected result using array Concatenation.
var string = "test,test2";
var array = string.split(",");
var finalArray=[[array[0]]].concat([[array[1]]])
console.log(JSON.stringify(finalArray));
What version of JavaScript are you targeting?
This might be a general answer:
var arr = "test,test2".split(",");
var i = arr.length;
while(i--)
arr[i] = [arr[i]];

How to remove character from last array element

I need to remove the last element comma in Javascript array
var arr = ["AAA,","BBB,"];
I need the result below
var arr = ["AAA,","BBB"];
Any help is appreciated...
var arr = ["AAA,","BBB,"];
arr[arr.length - 1] = arr[arr.length - 1].replace(',', '');
console.log(arr);
Simply use with replace()
var arr = ["AAA,","BBB,"];
arr[arr.length-1] = arr[arr.length-1].replace(/\,/g,"");
console.log(arr)
One of the other way is this:
var arr = ["AAA,",",BBB,"];
arr.push(arr.pop().replace(/,$/, ''));
console.log(arr);
This answer explains how you can do it using regex:
>> var str = "BBB,"
>> str = str.replace(/,[^,]*$/ , "")
>> str
>> "BBB"
var arr = ["AAA,","BBB,"];
var lastelmnt = arr[(arr.length)-1].replace(',', '');
arr.splice(((arr.length)-1),1,lastelmnt);
Output :
["AAA,", "BBB"]
arr[arr.length-1] = arr[arr.length-1].slice(0,-1)
using JavaScript string split() method & Array splice() method.
DEMO
var arr = ["AAA,","BBB,"];
var arrLastElement = arr[arr.length-1];
var splitStr = arrLastElement.split(',');
var strWithoutComma = splitStr[0];
arr.splice(arr.length-1);
arr.push(strWithoutComma);
console.log(arr);

I want to convert the below array

I want to convert the below array:
["A:100","B:234","C:124","D:634","E:543","F:657"];
Into:
["100:234:124:634:543:657"];
How to do this?
So not sure why you would want that particular output since it would just be a single item in an array but this should work:
var testArray = ["A:100","B:234","C:124","D:634","E:543","F:657"];
var resultArray = [];
for(var i = 0; i < testArray.length; ++i) {
resultArray.push(testArray[i].split(':')[1]);
}
var strValue = resultArray.join(':');
console.log(strValue);
resultArray = [strValue];
console.log(resultArray);
You could iterate the array, return the number on the right and join it with ':'.
var data = ["A:100","B:234","C:124","D:634","E:543","F:657"],
result = [data.map(function (a) {
return a.match(/\d*$/);
}).join(':')];
console.log(result);
Or a bit shorter
var data = ["A:100","B:234","C:124","D:634","E:543","F:657"],
result = [data.map(RegExp.prototype.exec.bind(/\d*$/)).join(':')];
console.log(result);
<script>
var arr=["A:100","B:234","C:124","D:634","E:543","F:657"];
var str='';
for(var i=0;i<arr.length;i++){
str+=arr[i].split(":")[1]+":";
}
console.log(str.substring(0, str.length - 1));
</script>
You could just keep the number behind ":" and join new elements with ":"
var data = ["A:100","B:234","C:124","D:634","E:543","F:657"];
var results = [data.map(x => x.split(":")[1]).join(":")];
console.log(results);
You join it with what you want :, split it by what you don't won't /\D\:/ (non digit followed by :), and then join it using an empty string '':
var arr = ["A:100","B:234","C:124","D:634","E:543","F:657"];
var result = [arr.join(':').split(/\D\:/).join('')];
console.log(result);

Regex for creating an array from String

I have a string as follows
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
I want to get three arrays from above string as follows
var arr1 = ["series-3","series-5","series-6"];
var arr2 = ["a3","a4","a5"];
var arr3 = ["class a", "class b"];
What regex should I use to achieve this?
Can this be done without regex?
Use String#split() method
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// split string based on comma followed by [
var temp = str.split(/,(?=\[)/);
// remove [ and ] from string usning slice
// then split using , to get the result array
var arr1 = temp[0].slice(1, -1).split(',');
var arr2 = temp[1].slice(1, -1).split(',');
var arr3 = temp[2].slice(1, -1).split(',');
console.log(arr1, arr2, arr3);
Or same method with some variation
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Remove [ at start and ] at end using slice
// and then split string based on `],[`
var temp = str.slice(1, -1).split('],[');
// then split using , to get the result array
var arr1 = temp[0].split(',');
var arr2 = temp[1].split(',');
var arr3 = temp[2].split(',');
console.log(arr1, arr2, arr3);
RegEx and String methods can be used. It's better to create an object and store individual arrays inside that object.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Match anything that is inside the `[` and `]`
var stringsArr = str.match(/\[[^[\]]*\]/g);
// Result object
var result = {};
// Iterate over strings inside `[` and `]` and split by the `,`
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var stringsArr = str.match(/\[[^[\]]*\]/g);
var result = {};
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
To create the global variables(Not recommended), just remove var result = {}; and replace result by window in the forEach.
I would prefer to do it like this
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]",
arrs = str.match(/[^[]+(?=])/g).map(s => s.split(","));
console.log(arrs);
Just for the fun of it, another way where we add the missing quotes and use JSON.parse to convert it to a multidimensional array.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var result = JSON.parse("[" + str.replace(/\[/g,'["').replace(/\]/g,'"]').replace(/([^\]]),/g,'$1","') + "]");
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);

Categories