Split string into array by several delimiters - javascript

Folks,
I have looked at underscore.string and string.js modules and still can't find a good way to do the following:
Suppose I have a query string string:
"!dogs,cats,horses!cows!fish"
I would like to pass it to a function that looks for all words that start with !, and get back an Array:
['dogs','cows','fish']
Similarly, the same function should return an array of words that start with ,:
['cats','horses]
Thanks!!!

You can use RegEx to easily match the split characters.
var string = "!dogs,cats,horses!cows!fish";
var splitString = string.split(/!|,/);
// ["dogs", "cats", "horses", "cows", "fish"]
The only issue with that is that it will possibly add an empty string at the beginning of the array if you start it with !. You could fix that with a function:
splitString.forEach(function(item){
if(item === ""){
splitString.splice(splitString.indexOf(item), 1)
}
});
EDIT:
In response to your clarificaiton, here is a function that does as you ask. It currently returns an object with the values commas and exclaim, each with an array of the corresponding elements.
JSBin showing it working.
function splitString(str){
var exclaimValues = [];
var expandedValues = [];
var commaValues = [];
var needsUnshift = false;
//First split the comma delimited values
var stringFragments = str.split(',');
//Iterate through them and see if they contain !
for(var i = 0; i < stringFragments.length; i++){
var stringValue = stringFragments[i];
// if the value contains an !, its an exclaimValue
if (stringValue.indexOf('!') !== -1){
exclaimValues.push(stringValue);
}
// otherwise, it's a comma value
else {
commaValues.push(stringValue);
}
}
// iterate through each exclaim value
for(var i = 0; i < exclaimValues.length; i++){
var exclaimValue = exclaimValues[i];
var expandedExclaimValues = exclaimValue.split('!');
//we know that if it doesn't start with !, the
// the first value is actually a comma value. So move it
if(exclaimValue.indexOf('!') !== 0) commaValues.unshift(expandedExclaimValues.shift());
for(var j = 0; j < expandedExclaimValues.length; j++){
var expandedExclaimValue = expandedExclaimValues[j];
//If it's not a blank entry, push it to our results list.
if(expandedExclaimValue !== "") expandedValues.push(expandedExclaimValue);
}
}
return {comma: commaValues, exclaim: expandedValues};
}
So if we do:
var str = "!dogs,cats,horses!cows!fish,comma!exclaim,comma2,comma3!exclaim2";
var results = splitString(str)
results would be:
{
comma: ["comma3", "comma", "horses", "cats", "comma2"],
exclaim: ["dogs", "cows", "fish", "exclaim", "exclaim2"]
}

Related

How to extract specific words from a string with some patterns?

I am trying to extract some strings from a word with some pattern like -
"38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"
how will I extract all word between - separately, means first word before - and then second word between - and - and so on...
string = "38384-1-page1-2222";
string.substr(0, string.indexof("-")); //return 38384
But how will I extract 1, page1 and 2222 all the words separately?
The javascript function str.split(separator) split the string by the given separator and it returns an array of all the splited string. REF Here
Here is an example following your question :
var string = "38384-1-page1-2222";
var separator = "-";
var separated = string.split(separator);
var firstString = separated[0]; // will be '38384'
var secondString = separated[1]; // will be '1'
var thirdString = separated[2]; // will be 'page1'
/* And So on ... */
Hope this can help
Use String.prototype.split() to get your string into array
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var resultArray = [];
for (let i = 0; i < words.length;i++) {
let temp = words[i];
resultArray = pushArray(temp.split("-"), resultArray)
}
console.log(resultArray)
function pushArray (inputArray, output) {
for (let i = 0; i < inputArray.length;i++) {
output.push(inputArray[i]);
}
return output;
}
Or simply use Array.prototype.reduce()
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var result = words.reduce((previousValue, currentValue) => previousValue.concat(currentValue.split("-")), [])
console.log(result)
You can use regex /[^-]+/g
const words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
console.log(words.map(v=>v.match(/[^-]+/g)).flat())

Javascript | Why does the variable equal undefined?

In this code largestGap is equal to undefined when it is logged. Basically this code is turning the string of 1s and 0s into an array and finding the largest gap between two 1s, as you can see looking through largestGap should equal 4, but as stated earlier it returns undefined.
var gaps = [];
var gapCount = 0;
var largestGap = gaps[0];
var string = '10010001000010001001';
string.split('');
var stringArray = Array.from(string);
stringArray.forEach(function(item, array) {
if (item == '1') {
if (gapCount > 0) {
gaps.push(gapCount);
}
gapCount = 0;
} else {
gapCount++;
}
});
for (i = 0; i < gaps.length; i++) {
if (largestGap < gaps[i]) {
largestGap = arr[i];
}
}
console.log(`The largest gap in the string is ${largestGap}`);
You initialize largestGap like:
var largestGap = gaps[0];
But the gaps array is empty initially. Initialize it only after the gaps array is populated, otherwise the test later (if (largestGap < gaps[i])) will not work.
There's also no arr variable. Use the gaps variable instead:
var gaps = [];
var gapCount = 0;
var string = '10010001000010001001';
var stringArray = Array.from(string);
stringArray.forEach(function(item, array) {
if (item == '1') {
if (gapCount > 0) {
gaps.push(gapCount);
}
gapCount = 0;
} else {
gapCount++;
}
});
var largestGap = 0;
for (i = 0; i < gaps.length; i++) {
if (largestGap < gaps[i]) {
largestGap = gaps[i];
}
}
console.log(`The largest gap in the string is ${largestGap}`);
Note that string.split(''); does nothing - it creates an array, and that array is never used, so you can remove that line.
This could be done much more concisely by matching 0s with a regular expression, then mapping the array of matched substrings to each match's length, then calling Math.max with that array of lengths:
const string = '10010001000010001001';
const matchLengths = (string.match(/0+/g) || []).map(str => str.length);
const largestGap = Math.max(...matchLengths);
console.log(`The largest gap in the string is ${largestGap}`);
The || [] is needed because, if there are no matches, the global regular expression match will return null rather than an empty array. If you're sure there will be at least one 0 in the string, you can remove that part to simplify things.
You are getting value from an empty array thats why first you should fill the gap array the use gap[0] insead of doing it before you even pushed anything to the array
you are assigning variables as
var gaps = [];
var gapCount = 0;
var largestGap = gaps[0];
So largestGap in the end also will have no value as it is assigned at the beginning when gaps variable had no value

How can I split this string of numbers with ranges?

I have a string of numbers like this:
var string= "1,2,3,4-8,15,17,18-21,22";
How can I split it into an array that forms: [1,2,3,4,5,6,7,8,15,17,18,19,20,21,22]
UPDATE:Okay, code coming up in just a bit... trying to get a jsfiddle up.
var mystring= "1,2,3,4-8,15,17,18-21,22";
var array1= mystring.split(",");
document.getElementById("output").innerHTML=array1;
var array2 = searchStringInArray ("-", array1);
document.getElementById("output2").innerHTML=array2;
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
So around here I got stuck and was thinking there should be a better way. I know you have to search the array for hyphen split strings. But I failed to get them into another array that i could then insert into the first array.
https://jsfiddle.net/08au43ka/
var string= "1,2,3,4-8,15,17,18-21,22";
var arr=string.split(",");
var crr=[];
arr.forEach(function(a){
brr= a.split("-");
if(brr.length==2){
var o=parseInt(brr[0]);
var p=parseInt(brr[1]);
for(var i=o;i<=p;i++)
crr.push(i);
}
else
crr.push(parseInt(brr[0]));
})
console.log(crr);
You could split first by comma, then by minus and reduce the whole to a new array with an inner loop for missing values.
var string = "1,2,3,4-8,15,17,18-21,22",
result = string.split(',').reduce(function (r, a) {
var b = a.split('-').map(Number);
do {
r.push(b[0]);
b[0]++;
} while (b[0] <= b[1]);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can just replace the ranges:
var string = "1,2,3,4-8,15,17,18-21,22"
var regexRanges = /(\d+)-(\d+)/g;
var getRangeValues = function(range, start, end) {
return Array(end - start + 1).fill(+start).map((x, i)=> x + i);
};
var result = JSON.parse('[' + string.replace(regexRanges, getRangeValues) + ']');
console.log(result);
var string= "1,2,3,4-8,15,17,18-21,22";
var chunks = string.split(",");
var numbers = [];
for (var i = 0; i < chunks.length; i++) {
var chunk = chunks[i];
if (chunk.indexOf('-') < 0) {
numbers.push(parseInt(chunk));
}
else {
var pair = chunk.split('-');
for (var j = pair[0]; j <= pair[1]; j++) {
numbers.push(parseInt(j));
}
}
}
console.log(numbers);
Since there is no known method for me to achieve what you want most likely you will need to write your own.
I'd split that string by commas, then i'd iterate through array looking for anything containing dash in it, if it contains dash grab that array item, parse it
get left side, get right side, create loop from i = left to i<right, push items into original array.

Comma Delimiter Multi Dimensional Array

I have an array (call it array[]), with elements of the following format separated by a comma:
array[0] = abc, def, 123, ghi
How can I pass this into another multi-dimensional array (lets say arrayTwo[]) such that arrayTwo is as follows:
arrayTwo[0][0] = "abc"
arrayTwo[0][1] = "def"
arrayTwo[0][2] = "123"
arrayTwo[0][3] = "ghi"
I am really unsure about the comma as a delimiter portion (use split()?). I believe the looping part should not be too difficult for me to handle. Thanks for any help!
You can split the items by ,\s* regex which is comma followed by zero or more spaces. This will create an array. Then just insert that array into the appropriate element of arrayTwo.
arrayTwo = array.map(function (item) {
return item.split(/,\s*/)
});
Unrolled slightly it would look like:
arrayTwo = [];
for (var x = 0; x < array.length; x++) {
var item = array[x].split(/,\s*/);
arrayTwo[x] = [];
for (var i = 0; i < item.length; i++) {
arrayTwo[x][i] = item[i];
}
}

Extract specific substring using javascript?

If I have the following string:
mickey mouse WITH friend:goofy WITH pet:pluto
What is the best way in javascript to take that string and extract out all the "key:value" pairs into some object variable? The colon is the separator. Though I may or may not be able to guarantee the WITH will be there.
var array = str.match(/\w+\:\w+/g);
Then split each item in array using ":", to get the key value pairs.
Here is the code:
function getObject(str) {
var ar = str.match(/\w+\:\w+/g);
var outObj = {};
for (var i=0; i < ar.length; i++) {
var item = ar[i];
var s = item.split(":");
outObj[s[0]] = s[1];
}
return outObj;
}
myString.split(/\s+/).reduce(function(map, str) {
var parts = str.split(":");
if (parts.length > 1)
map[parts.shift()] = parts.join(":");
return map;
}, {});
Maybe something like
"mickey WITH friend:goofy WITH pet:pluto".split(":")
it will return the array, then Looping over the array.
The string pattern has to be consistent in one or the other way atleast.
Use split function of javascript and split by the word that occurs in common(our say space Atleast)
Then you need to split each of those by using : as key, and get the required values into an object.
Hope that's what you were long for.
You can do it this way for example:
var myString = "mickey WITH friend:goofy WITH pet:pluto";
function someName(str, separator) {
var arr = str.split(" "),
arr2 = [],
obj = {};
for(var i = 0, ilen = arr.length; i < ilen; i++) {
if ( arr[i].indexOf(separator) !== -1 ) {
arr2 = arr[i].split(separator);
obj[arr2[0]] = arr2[1];
}
}
return obj;
}
var x = someName(myString, ":");
console.log(x);

Categories

Resources