Hi I'm trying to split a string based on multiple delimiters.Below is the code
var data="- This, a sample string.";
var delimiters=[" ",".","-",","];
var myArray = new Array();
for(var i=0;i<delimiters.length;i++)
{
if(myArray == ''){
myArray = data.split(delimiters[i])
}
else
{
for(var j=0;j<myArray.length;j++){
var tempArray = myArray[j].split(delimiters[i]);
if(tempArray.length != 1){
myArray.splice(j,1);
var myArray = myArray.concat(tempArray);
}
}
}
}
console.log("info","String split using delimiters is - "+ myArray);
Below is the output that i get
a,sample,string,,,,This,
The output that i should get is
This
a
sample
string
I'm stuck here dont know where i am going wrong.Any help will be much appreciated.
You could pass a regexp into data.split() as described here.
I'm not great with regexp but in this case something like this would work:
var tempArr = [];
myArray = data.split(/,|-| |\./);
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] !== "") {
tempArr.push(myArray[i]);
}
}
myArray = tempArr;
console.log(myArray);
I'm sure there's probably a way to discard empty strings from the array in the regexp without needing a loop but I don't know it - hopefully a helpful start though.
Here you go:
var data = ["- This, a sample string."];
var delimiters=[" ",".","-",","];
for (var i=0; i < delimiters.length; i++) {
var tmpArr = [];
for (var j = 0; j < data.length; j++) {
var parts = data[j].split(delimiters[i]);
for (var k = 0; k < parts.length; k++) {
if (parts[k]) {
tmpArr.push(parts[k]);
}
};
}
data = tmpArr;
}
console.log("info","String split using delimiters is - ", data);
Check for string length > 0 before doing a concat , and not != 1.
Zero length strings are getting appended to your array.
Related
I want to do the following:
The string 'London' needs to be printed acording to this logic:
'L'
'Lo'
'Lon'
'Lond'
'Londo'
'London'
An array or loop is what I have in mind, but a can't get it right. Someone who can help?
A simple loop would do it.
Use Array.prototype.slice (https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) to get the wanted portion of the string.
const string = 'London';
for (let i = 0; i < string.length; i++) {
console.log(string.slice(0,i+1));
}
A easy way of using substring method.
const str = "LONDON";
for (let i =0; i<= str.length ;){
console.log(str.substring(0,i++));
}
You may found it strange with using i <= str.length because str.substring(0,0) return empty string "",
You can change to :
const str = "LONDON";
for (let i =0; i< str.length ;){
console.log(str.substring(0,++i));
}
You could use two for loops. One to iterate through all the positions of "London", and the other to iterate through portions of the word "London". Take a look at the code snippet bellow:
var word = "London";
for (var i = 0; i < word.length; i++) {
var str = "";
for (var j = 0; j <= i; j++) {
str += word[j];
}
console.log(str);
}
Below code will be work fine for your problem.
var a = "LONDON";
a = a.split('');
var str = '';
for (var i = 0; i < a.length; i++) {
str += a[i];
console.log(str);
}
Happy Coding!!
I have array of regex pattern, i want to check the url which matches the regex and use it.
please let me know the best way to do it.
The code i have written is something like this.
var a = ['^\/(.*)\/product_(.*)','(.*)cat_(.*)'];
var result = a.exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346");
Expected:
when i use a.exec it should parse the url "/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346"
and give results.
Iterate over the regexes like this:
var a = ['^\/(.*)\/product_(.*)','(.*)cat_(.*)'];
var result = [];
for (var i = 0; i < a.length; i++) {
result.push(RegExp(a[i]).exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346"));
}
All matches are then stored in result.
result[0] is a array with matches from the regex in a at index 0, result[1] --> a[1], etc. If there are no results from the regex, result[x] will be null.
Instead of pushing the regex result to a array, you could also work on the result directly:
for (var i = 0; i < a.length; i++) {
var currentResult = RegExp(a[i]).exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346");
// Do stuff with currentResult here.
}
You can loop over your regex array:
var a = [/^\/(.*)\/product_(.*)/, /(.*)cat_(.*)/];
var results = [];
for (var i = 0; i < a.length; i++) {
var result = a[i].exec("/Duracell-Coppertop-Alkaline-AA-24-Pack/product_385346");
results.push(result);
}
console.log(results);
I have surfed the problem but couldn't get any possible solution ..
Let's say i have a var like this
var data = [
{
'a':10,
'b':20,
'c':30
},
{
'a':1,
'b':2,
'c':3
},
{
'a':100,
'b':200,
'c':300
}];
Now , i need a multidimensional array like
var values = [[10,1,100], //a
[20,2,200], //b
[30,3,300]]; //c
What i have tried is
var values = [];
for(var key in data[0])
{
values.push([]); // this creates a multidimesional array for each key
for(var i=0;i<data.length;i++)
{
// how to push data[i][key] in the multi dimensional array
}
}
Note : data.length and number of keys keeps changing and i just want to be done using push() without any extra variables. Even i don't want to use extra for loops
If you guys found any duplicate here , just put the link as comment without downvote
Try this:
var result = new Array();
for(var i = 0; i < data.length; i++) {
var arr = new Array();
for(var key in data[i]) {
arr.push(data[i][key]);
}
result.push(arr);
}
also if you don't want the 'arr' variable just write directly to the result, but in my opinion code above is much more understandable:
for(var i = 0; i < data.length; i++) {
result.push(new Array());
for(var key in data[i]) {
result[i].push(data[i][key]);
}
}
Ok, based on your comment I have modified the the loop. Please check the solution and mark question as answered if it is what you need. Personally I don't understand why you prefer messy and hard to understand code instead of using additional variables, but that's totally different topic.
for(var i = 0; i < data.length; i++) {
for(var j = 0; j < Object.keys(data[0]).length; j++) {
result[j] = result[j] || new Array();
console.log('result[' + j + '][' + i + ']' + ' = ' + data[i][Object.keys(data[i])[j]])
result[j][i] = data[i][Object.keys(data[i])[j]];
}
}
Ok i'v been trying many deferent things to get this to work.
I need a string separated by commas into a 2 dimensional array... like this for example:
string = "a,b,c,d,e,1,2,3,4,5";
array = [['a','1'],['b','2'],['c','3'],['d','4'],['e','5']];
This is the code I have been tweaking.
var temp = list.split(',');
questions = [[''],[''],[''],[''],['']];
five = 0;
one = 0;
for(var i = 0; i < temp.length; i++) {
if(one == 5){five++; one = 0;}
one++;
questions[one][five] = temp[i];
}
btw list = "a,b,c,d,e,1,2,3,4,5".
Thank's in advance!!!
I'd suggest a slightly different approach, that avoids the (to my mind overly-) complex internals of the for loop:
var string = "a,b,c,d,e,1,2,3,4,5",
temp = string.split(','),
midpoint = Math.floor(temp.length/2),
output = [];
for (var i=0, len=midpoint; i<len; i++){
output.push([temp[i], temp[midpoint]]);
midpoint++;
}
console.log(output);
JS Fiddle demo.
OK so i fixed it before i asked the question... but i did so much work i'll post it anyway.
This is the code i have now that works:
var temp = list.split(',');
questions = [[],[],[],[],[]];
for(var i = 0; i < temp.length; i++) {
questions[i%5][Math.floor(i/5)] = temp[i];
one++;
}
Thank You Barmar!!!
function split(str)
{
var array = str.split(';');
var test[][] = new Array();
for(var i = 0; i < array.length; i++)
{
var arr = array[i].split(',');
for(var j = 0; j < arr.length; j++)
{
test[i][j]=arr[j];
}
}
}
onchange="split('1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i')"
it was not working. i need to split this string to 6*3 multi dimentional array
var array[][] = new Array() is not valid syntax for declaring arrays. Javascript arrays are one dimensional leaving you to nest them. Which means you need to insert a new array into each slot yourself before you can start appending to it.
Like this: http://jsfiddle.net/Squeegy/ShWGB/
function split(str) {
var lines = str.split(';');
var test = [];
for(var i = 0; i < lines.length; i++) {
if (typeof test[i] === 'undefined') {
test[i] = [];
}
var line = lines[i].split(',');
for(var j = 0; j < line.length; j++) {
test[i][j] = line[j];
}
}
return test;
}
console.log(split('a,b,c;d,e,f'));
var test[][] is an invalid javascript syntax.
To create a 2D array, which is an array of array, just declare your array and push arrays into it.
Something like this:
var myArr = new Array(10);
for (var i = 0; i < 10; i++) {
myArr[i] = new Array(20);
}
I'll let you apply this to your problem. Also, I don't like the name of your function, try to use something different from the standards, to avoid confusion when you read your code days or months from now.
function split(str)
{
var array = str.split(';'),
length = array.length;
for (var i = 0; i < length; i++) array[i] = array[i].split(',');
return array;
}
Here's the fiddle: http://jsfiddle.net/AbXNk/
var str='1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var arr=str.split(";");
for(var i=0;i<arr.length;i++)arr[i]=arr[i].split(",");
Now arr is an array with 6 elements and each element contain array with 3 elements.
Accessing element:
alert(arr[4][2]); // letter "f" displayed