Create an array of string from a string - javascript

I'm trying to create arrays from the following strings:
"[DHKSGFKDBF][JDKDFJ][NDKDHDLSJD]" // ["DHKSGFKDBF", "JDKDFJ", "NDKDHDLSJD"]
"[ADJDJKDFJ][JEJZJDUDU]" // ["ADJDJKDFJ", "JEJZJDUDU"]
"[ADJDJKDFJ]" // ["ADJDJKDFJ"]
There is a simple way to do this?

There are a bunch of ways to do it. Easiest would be remove the outside one and split.
var str = "[DHKSGFKDBF][JDKDFJ][NDKDHDLSJD]"
var arr = str.slice(1,str.length-1).split('][');
console.log(arr);

var str = "[DHKSGFKDBF][JDKDFJ][NDKDHDLSJD]"
var array = str.substring(1,str.length-1).split("][");
console.log(array);
results into:
["DHKSGFKDBF", "JDKDFJ", "NDKDHDLSJD"]

You can replace all non-alphanumeric characters (/\W+/g) with a delimiter (,), split on the delimiter, and then filter out the nulls (!v) at the beginning and end.
const inputs = [
"[DHKSGFKDBF][JDKDFJ][NDKDHDLSJD]", // ["DHKSGFKDBF","JDKDFJ","NDKDHDLSJD"]
"[ADJDJKDFJ][JEJZJDUDU]", // ["ADJDJKDFJ","JEJZJDUDU"]
"[ADJDJKDFJ]" // ["ADJDJKDFJ"]
]
const convert = s => s.replace(/\W+/g, ',').split(',').filter(v => !!v);
inputs.forEach(input => console.log(JSON.stringify(convert(input))));
.as-console-wrapper { top: 0; max-height: 100% !important; }

You can use string.match function.
var str = "[DHKSGFKDBF][JDKDFJ][NDKDHDLSJD]";
console.log(str.match(/\[(.*?)\]/g).map(item => item.substring(1, item.length - 1)));

Once you have checked the correct format of the string (i.e. starting with [ and ending with ]), you could remove the leading [ and the closing ] and split by ][, e.g.:
[
"[DHKSGFKDBF][JDKDFJ][NDKDHDLSJD]",
"[ADJDJKDFJ][JEJZJDUDU]",
"[ADJDJKDFJ]",
""
].forEach(str => {
console.log(splitStr(str));
});
function splitStr(str) {
if (str && str.length > 2 && str.charAt(0) == '[' && str.charAt(str.length - 1) == ']') {
return str.substring(1, str.length - 1).split('][');
}
return [];
}

Related

how to do array split with regex?

i have a string i need to convert it into a array of object
const str = "addias (brand|type) sneakers(product) for men(o)"
expected output
let output = [
{
key:"addias",
value:["brand","type"]
},
{
key:"sneakers",
value:["product"]
},
{
key:"for men",
value:[]
}
]
code i tried
function gerateSchema(val) {
let split = val.split(" ")
let maps = split.map((i) => {
let obj = i.split("(")
let key = obj[0].replaceAll(/\s/g, "")
let cleanValue = obj[1].replace(/[{()}]/g, "")
let stripedValues = cleanValue.split("|")
return {
key: key,
value: stripedValues,
}
})
return maps
}
let out = gerateSchema(str)
but this breaking when there is some word with space for example for men
how to do split with a regex
One approach would be first do a regex find all to find all key/value combinations in the original string. Then, iterate that result and build out a hashmap using the word keys and the array values.
var str = "addias (brand|type) sneakers(product) for men(o)";
var matches = str.match(/\w+(?: \w+)*\s*\(.*?\)/g, str);
var array = [];
for (var i=0; i < matches.length; ++i) {
var parts = matches[i].split(/\s*(?=\()/);
var map = {};
map["key"] = parts[0];
map["value"] = parts[1].replace(/^\(|\)$/g, "").split(/\|/);
array.push(map);
}
console.log(array);
The first regex matches each key/value string:
\w+ match a word
(?: \w+)* followed by a space, and another word, the quantity zero or more times
\s* optional whitespace
\( (
.*? pipe separated value string
\) )
Then, we split each term on \s*(?=\(), which is the space(s) immediately preceding the (...|...) term. Finally, we split the value string on pipe | to generate the set of values.
An alternative way could be this.
const str = "addias (brand|type) sneakers(product) for men(o)"
const array = str.split(')').filter(i => i.length).map(i => {
const item = i.split('(');
return {
key: item[0].trim(),
value: item[1].split('|')
}
})
console.log(array)
It may be simpler to use the exec method to iterate over the patterns the regex finds.
const str = 'addias(brand|type|size|color) sneakers(pro) for men(o)';
// The regex looks for an initial group of letters,
// then matches the string inside the parentheses
const regex = /([a-z]+)\(([a-z\|]+)\)/g;
let myArray;
const arr = [];
while ((myArray = regex.exec(str)) !== null) {
// Destructure out the key and the delimited string
const [_, key, ...rest] = myArray;
// `split` on the string found in `rest` first element
const values = rest[0].split('|');
// Finally push a new object into the output array
// (removing "o" for whatever reason)
arr.push({
key,
value: values.filter(v => v !== 'o')
});
}
console.log(arr);
With a little help from regex101.com, derived the following regex expressions and the following code.
([^\(]+)\(([^\)]*)\) which breaks down into
([^\(]+) - capture 1 or more chars up to the first ( as group 1
\( - swallow the left parens
([^\)]*) - capture everything up to the next occurrence of ) as group 2
\) - swallow the right parens
and I was starting to [^|]+ - to parse the text of group 2, but it's actually simpler with a simple split statement.
function generateSchema(str) {
const regex = /([^\(]+)\(([^\)]*)\)/mg; // captures the 'word (word)' pattern
let m;
let output = [];
let obj = {};
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
m.forEach((match, groupIndex) => {
if (groupIndex === 1) {
obj = {};
obj.key = match.trim();
} else if (groupIndex === 2) {
obj.value = match.split('|').map(i=>i.trim());
output.push(obj);
}
});
}
return output;
}
const str = "addidas (brand | type ) sneakers(product) for men(o)";
console.log(generateSchema(str));

How to join strings in a for loop in Javascript?

I am trying to capitalise the first character of each word and join all words into one string. I have managed to capitalise the first character of each word but cant seem to get .join() to work on the final result
function generateHashtag (str) {
let split = str.split(' ')
for(let i = 0; i < split.length; i++){
let finalResult = split[i].charAt(0).toUpperCase() + split[i].substring(1)
console.log(finalResult.join(''))
}
}
console.log(generateHashtag('Hello my name is')) should return ('HelloMyNameIs')
Achieving this by split is possible. first create an array of divided strings (by the delimiter ' ') and then loop around the array and capitalize the first char using the method toUpperCase and concat the rest of the string without the first letter using slice
function generateHashtag(str) {
let split = str.split(' ');
for (let i = 0; i < split.length; i++) {
split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
}
return split.join('');
}
console.log(generateHashtag('Hello my name is'));
More about split - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
you can do split[i] = split[i].charAt(0).toUpperCase() + split[i].substring(1) in the loop then outside loop do split.join('')
Basically you are replacing each word (split[i]) with capitalised word. Then in the end join the words.
finalResult is a String, not an Array so there is no join function.
Use this instead :
function generateHashtag (str) {
let arrayWords = str.split(' ')
const titleCasedArray = arrayWords.map(word => titleCaseWord(word))
return titleCasedArray.join('');
}
function titleCaseWord (word){
return word.slice(0,1).toUpperCase() + word.slice(1,-1).toLowerCase()
}
You can do something like this:
function generateHashtag (str) {
//returns array of strings
let split = str.split(' ')
//returns array of strings with each word capitalized
const capitalizedWordsArr = split.map( word => word.charAt(0).toUpperCase() + word.substring(1))
//returns a string by joining above array with no spaces
return capitalizedWordsArr.join('')
}
This is a perfect use-case for Array.prototype.reduce:
function generateHashtag(str) {
return str
.split(' ')
.reduce((acc, [firstLetter, ...rest]) => acc += `${firstLetter.toUpperCase()}${rest.join('')}`,
''
);
}
console.log(generateHashtag('Hello my name is')); // should return ('HelloMyNameIs')
Javascript strings are immutable so you cannot overwrite them on the go, but you can overwrite array elements.
By using String.prototype.substr() you can extract a part of the string, you can use these parts, modify it and create a new string then replace the old array element. finally returning the joined string like you wanted to
function generateHashtag(str) {
const split = str.split(' ') // array of words
for (let i = 0; i < split.length; i++)
split[i] = split[i].substr(0, 1).toUpperCase() + split[i].substr(1); // overwriting existing elements with Titlecased words
return split.join(''); // returning final string
}
console.log(generateHashtag('Hello my name is'))
You don't need to use join at all, just declare and initialize finalResult outside the loop and concatenate each word inside the loop:
function generateHashtag(str) {
const split = str.split(' '); // Array<String>
let finalResult = ''; // String
for(let i = 0; i < split.length; i++) {
const titleCased = split[i].charAt(0).toUpperCase() + split[i].substring(1);
finalResult += titleCased;
}
return finalResult;
}
console.log(generateHashtag('Hello my name is'));
However, you can simplify this code considerably by using a functional-programming (FP) style with map and reduce. See below.
I've also changed your code to use toLocaleUpperCase instead of toUpperCase and uses [0] for brevity.
It's still safe to use substring(1) for single-character strings, it just returns ''.
function generateHashtag(str) {
return ( str
.split(' ')
.map( word => word[0].toLocaleUpperCase() + word.substring(1).toLocaleLowerCase() )
.reduce( ( word, concat ) => concat + word, "" )
);
}
I forgot that join() can still be used instead of reduce (and will have an optimized implementation inside the JS engine anyway):
I've also moved the map function's logic to a named function toTitleCase.
function generateHashtag(str) {
const toTitleCase( word ) => word[0].toLocaleUpperCase() + word.substring(1).toLocaleLowerCase();
return ( str
.split(' ')
.map( word => toTitleCase( word ) ) // or just `.map( toTitleCase )`
.join()
);
}
The return statement has parens to prevent unwanted automatic-semicolon-insertion which would otherwise break the function.
If you want something similar to your code, but working, i would do this:
function generateHashtag (str) {
let split = str.split(' ')
let newStr = []
for (let i = 0; i < split.length; i++){
newStr.push(split[i].charAt(0).toUpperCase() + split[i].substring(1))
}
return newStr.join('')
}
You could also choose to do this task using a 'regular expression'.
https://cheatography.com/davechild/cheat-sheets/regular-expressions/
Here is a quick implementation:
const generateHashtag = str => {
// regular expression to capitalize the words
const regEx = /(\b[a-z](?!\s))/g
str = str.replace(regEx, (char) => {
return char.toUpperCase()
});
// remove spaces, return
return str.split(' ').join('')
}
Same code, but with less readability:
const generateHashtag = str => {
return str.replace(/(\b[a-z](?!\s))/g, (char) => {
return char.toUpperCase()
}).split(' ').join('');
}
function generateHashtag (str) {
return str.replace(/\b\S/g, e => e.toUpperCase()).replace(/\s/g,'');
}
console.log(generateHashtag('Hello my name is'))
\b: bondary \S: non space \s: space.
https://regex101.com/
//try this code solve your problem
const generateHashtag = str => {
let split = str.split(' ')
let finalResult = []
for (word of split) {
finalResult.push(word[0].toUpperCase() + word.substring(1))
}
return finalResult.join('')
}
console.log(generateHashtag('Hello my name is'))

How to flip every character with the character next to it. Javascript

Need help inside the for loop to flip each character with the character before it.
function flip(str) {
//split string
//iterate through split string
//return joined string
var splitt = str.split('');
for(var i = 0; i < splitt.length; i++){
//flip every character with one before it
}
}
var output = flip('otatl');
console.log(output); // -> 'total'
function split(str) {
let splitt = str.split('');
for (let i=0; i<splitt.length-1; i+=2) {
const temp = splitt[i];
splitt[i] = splitt[i+1];
splitt[i+1] = temp;
}
return splitt.join('');
}
You can use ES6 destructuring assignment.
function flip(str) {
//split string
//iterate through split string
//return joined string
let splitt = str.split('');
for (let i=0; i < splitt.length; i++){
//flip every character with one before it
if (i%2 == 1) {
[splitt[i-1], splitt[i]] = [splitt[i], splitt[i-1]];
}
}
return splitt.join('');
}
let output = flip('otatl');
console.log(output); // -> 'total'
You can combine this technique with gillyb's loop pattern to reduce the iterations as follows:
function flip(str) {
//split string
//iterate through split string
//return joined string
let splitt = str.split('');
for (let i=1; i < splitt.length; i+=2){
//flip every character with one before it
[splitt[i-1], splitt[i]] = [splitt[i], splitt[i-1]];
}
return splitt.join('');
}
let output = flip('otatl');
console.log(output); // -> 'total'
Can do something similar with regex and array manipulation
const flip = (stringToFlip) => stringToFlip
.split(/(.{2})/) // array of strings of 2 chars
.map((e) => e.split('') // convert each string piece to array
.reverse() // reverse array
.join('') // convert array piece back to string
)
.join(''); // combine all parts
const result = flip('otatl');
console.log("flip('otatl')");
console.log(result);
If we're not restricted to for loops, this is my (slightly too code golf-ish?) answer:
const flip = (str) =>
str
.split('')
.reduce((a, v, i) => (a[i + ((i % 2) * -2 + 1)] = v, a), [])
.join('');
console.log(flip('otatl'));
console.log(flip('lfpi'));
I'm sorry I am late to the party but you can use reduce().
let input = "vanjskojfdghpja";
let output = input
.split('')
.reduce(([o,p],c,i) => i%2?[o+c+p,'']:[o,c],['',''])
.join('');
console.log(output);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Convert javascript string to array

I have string like this
'10:00','13:00','12:00','15:00','08:00','12:00'
I need it in format like this
Array(3)
Array[0] ['10:00', '13:00']
Array[1] ['12:00', '15:00']
Array[2] ['08:00', '12:00']
I tried with split method but without success.
You could replace single quotes with double quotes, add brackes and parse it as JSON and get an array, which is the grouped by two elements.
var string = "'10:00','13:00','12:00','15:00','08:00','12:00'",
array = JSON
.parse('[' + string.replace(/'/g, '"') + ']')
.reduce((r, s, i) => r.concat([i % 2 ? r.pop().concat(s) : [s]]), []);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var str = "'10:00','13:00','12:00','15:00','08:00','12:00'";
var oldArray = str.split(',');
var newArray = [];
while(oldArray.length){
let start = 0;
let end = 2;
newArray.push(oldArray.slice(start, end));
oldArray.splice(start, end);
}
console.log(newArray);
How about:
"'10:00','13:00','12:00','15:00','08:00','12:00'"
.replace(/'/g, '').replace(/(,[^,]*),/g,"$1;")
.split(';').map(itm => itm.split(','))
In this case you want to compare 2 values.
To do this you can make a for loop that reads the current value and the last value and compares the two.
If the last value is higher than current value, the splitting logic happens.
Either you add the current value to the last item (which is an array of strings) in the results array or you add a new array of strings at the end of the results array.
One potential solution:
let S = "'10:00','13:00','12:00','15:00','08:00','12:00'";
let R = S.split(',');
let I = 0;
let A = new Array([],[],[]);
R.map((object, index) => {
A[I][index % 2] = R[index];
if (index % 2 == 1) I++;
});
console.log(A);
You can use String.split(',') to split into individual values, then group them based on their positions (result of integer division with 2).
I am using groupBy from 30 seconds of code (disclaimer: I am one of the maintainers of the project/website) to group the elements based on the integer division with 2. Short explanation:
Use Array.map() to map the values of an array to a function or property name. Use Array.reduce() to create an object, where the keys are produced from the mapped results.
The result is an object, but can be easily converted into an array using Object.values() as shown below:
var data = "'10:00','13:00','12:00','15:00','08:00','12:00'";
const groupBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
acc[val] = (acc[val] || []).concat(arr[i]);
return acc;
}, {});
var arr = data.split(',');
arr = groupBy(arr, (v, i) => Math.floor(i / 2));
arr = Object.values(arr);
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I think use JSON.parse is better:
var array = "'10:00','13:00','12:00','15:00','08:00','12:00'";
array = JSON.parse( '[' + array.replace(/'/g,'"') + ']' );
var array2 = [];
for(var i=0;i < array.length - 1; i++){
array2.push([array[i], array[i+1]]);
}
console.log(array2);

Javascript How to split string by symbols count [duplicate]

As the title says, I've got a string and I want to split into segments of n characters.
For example:
var str = 'abcdefghijkl';
after some magic with n=3, it will become
var arr = ['abc','def','ghi','jkl'];
Is there a way to do this?
var str = 'abcdefghijkl';
console.log(str.match(/.{1,3}/g));
Note: Use {1,3} instead of just {3} to include the remainder for string lengths that aren't a multiple of 3, e.g:
console.log("abcd".match(/.{1,3}/g)); // ["abc", "d"]
A couple more subtleties:
If your string may contain newlines (which you want to count as a character rather than splitting the string), then the . won't capture those. Use /[\s\S]{1,3}/ instead. (Thanks #Mike).
If your string is empty, then match() will return null when you may be expecting an empty array. Protect against this by appending || [].
So you may end up with:
var str = 'abcdef \t\r\nghijkl';
var parts = str.match(/[\s\S]{1,3}/g) || [];
console.log(parts);
console.log(''.match(/[\s\S]{1,3}/g) || []);
If you didn't want to use a regular expression...
var chunks = [];
for (var i = 0, charsLength = str.length; i < charsLength; i += 3) {
chunks.push(str.substring(i, i + 3));
}
jsFiddle.
...otherwise the regex solution is pretty good :)
str.match(/.{3}/g); // => ['abc', 'def', 'ghi', 'jkl']
Building on the previous answers to this question; the following function will split a string (str) n-number (size) of characters.
function chunk(str, size) {
return str.match(new RegExp('.{1,' + size + '}', 'g'));
}
Demo
(function() {
function chunk(str, size) {
return str.match(new RegExp('.{1,' + size + '}', 'g'));
}
var str = 'HELLO WORLD';
println('Simple binary representation:');
println(chunk(textToBin(str), 8).join('\n'));
println('\nNow for something crazy:');
println(chunk(textToHex(str, 4), 8).map(function(h) { return '0x' + h }).join(' '));
// Utiliy functions, you can ignore these.
function textToBin(text) { return textToBase(text, 2, 8); }
function textToHex(t, w) { return pad(textToBase(t,16,2), roundUp(t.length, w)*2, '00'); }
function pad(val, len, chr) { return (repeat(chr, len) + val).slice(-len); }
function print(text) { document.getElementById('out').innerHTML += (text || ''); }
function println(text) { print((text || '') + '\n'); }
function repeat(chr, n) { return new Array(n + 1).join(chr); }
function textToBase(text, radix, n) {
return text.split('').reduce(function(result, chr) {
return result + pad(chr.charCodeAt(0).toString(radix), n, '0');
}, '');
}
function roundUp(numToRound, multiple) {
if (multiple === 0) return numToRound;
var remainder = numToRound % multiple;
return remainder === 0 ? numToRound : numToRound + multiple - remainder;
}
}());
#out {
white-space: pre;
font-size: 0.8em;
}
<div id="out"></div>
If you really need to stick to .split and/or .raplace, then use /(?<=^(?:.{3})+)(?!$)/g
For .split:
var arr = str.split( /(?<=^(?:.{3})+)(?!$)/ )
// [ 'abc', 'def', 'ghi', 'jkl' ]
For .replace:
var replaced = str.replace( /(?<=^(?:.{3})+)(?!$)/g, ' || ' )
// 'abc || def || ghi || jkl'
/(?!$)/ is to not stop at end of the string. Without it's:
var arr = str.split( /(?<=^(?:.{3})+)/ )
// [ 'abc', 'def', 'ghi', 'jkl' ] // is fine
var replaced = str.replace( /(?<=^(.{3})+)/g, ' || ')
// 'abc || def || ghi || jkl || ' // not fine
Ignoring group /(?:...)/ is to prevent duplicating entries in the array. Without it's:
var arr = str.split( /(?<=^(.{3})+)(?!$)/ )
// [ 'abc', 'abc', 'def', 'abc', 'ghi', 'abc', 'jkl' ] // not fine
var replaced = str.replace( /(?<=^(.{3})+)(?!$)/g, ' || ' )
// 'abc || def || ghi || jkl' // is fine
My solution (ES6 syntax):
const source = "8d7f66a9273fc766cd66d1d";
const target = [];
for (
const array = Array.from(source);
array.length;
target.push(array.splice(0,2).join(''), 2));
We could even create a function with this:
function splitStringBySegmentLength(source, segmentLength) {
if (!segmentLength || segmentLength < 1) throw Error('Segment length must be defined and greater than/equal to 1');
const target = [];
for (
const array = Array.from(source);
array.length;
target.push(array.splice(0,segmentLength).join('')));
return target;
}
Then you can call the function easily in a reusable manner:
const source = "8d7f66a9273fc766cd66d1d";
const target = splitStringBySegmentLength(source, 2);
Cheers
const chunkStr = (str, n, acc) => {
if (str.length === 0) {
return acc
} else {
acc.push(str.substring(0, n));
return chunkStr(str.substring(n), n, acc);
}
}
const str = 'abcdefghijkl';
const splittedString = chunkStr(str, 3, []);
Clean solution without REGEX
My favorite answer is gouder hicham's. But I revised it a little so that it makes more sense to me.
let myString = "Able was I ere I saw elba";
let splitString = [];
for (let i = 0; i < myString.length; i = i + 3) {
splitString.push(myString.slice(i, i + 3));
}
console.log(splitString);
Here is a functionalized version of the code.
function stringSplitter(myString, chunkSize) {
let splitString = [];
for (let i = 0; i < myString.length; i = i + chunkSize) {
splitString.push(myString.slice(i, i + chunkSize));
}
return splitString;
}
And the function's use:
let myString = "Able was I ere I saw elba";
let mySplitString = stringSplitter(myString, 3);
console.log(mySplitString);
And it's result:
>(9) ['Abl', 'e w', 'as ', 'I e', 're ', 'I s', 'aw ', 'elb', 'a']
try this simple code and it will work like magic !
let letters = "abcabcabcabcabc";
// we defined our variable or the name whatever
let a = -3;
let finalArray = [];
for (let i = 0; i <= letters.length; i += 3) {
finalArray.push(letters.slice(a, i));
a += 3;
}
// we did the shift method cause the first element in the array will be just a string "" so we removed it
finalArray.shift();
// here the final result
console.log(finalArray);
var str = 'abcdefghijkl';
var res = str.match(/.../g)
console.log(res)
here number of dots determines how many text you want in each word.
function chunk(er){
return er.match(/.{1,75}/g).join('\n');
}
Above function is what I use for Base64 chunking. It will create a line break ever 75 characters.
Here we intersperse a string with another string every n characters:
export const intersperseString = (n: number, intersperseWith: string, str: string): string => {
let ret = str.slice(0,n), remaining = str;
while (remaining) {
let v = remaining.slice(0, n);
remaining = remaining.slice(v.length);
ret += intersperseWith + v;
}
return ret;
};
if we use the above like so:
console.log(splitString(3,'|', 'aagaegeage'));
we get:
aag|aag|aeg|eag|e
and here we do the same, but push to an array:
export const sperseString = (n: number, str: string): Array<string> => {
let ret = [], remaining = str;
while (remaining) {
let v = remaining.slice(0, n);
remaining = remaining.slice(v.length);
ret.push(v);
}
return ret;
};
and then run it:
console.log(sperseString(5, 'foobarbaztruck'));
we get:
[ 'fooba', 'rbazt', 'ruck' ]
if someone knows of a way to simplify the above code, lmk, but it should work fine for strings.
Coming a little later to the discussion but here a variation that's a little faster than the substring + array push one.
// substring + array push + end precalc
var chunks = [];
for (var i = 0, e = 3, charsLength = str.length; i < charsLength; i += 3, e += 3) {
chunks.push(str.substring(i, e));
}
Pre-calculating the end value as part of the for loop is faster than doing the inline math inside substring. I've tested it in both Firefox and Chrome and they both show speedup.
You can try it here
Here's a way to do it without regular expressions or explicit loops, although it's stretching the definition of a one liner a bit:
const input = 'abcdefghijlkm';
// Change `3` to the desired split length.
const output = input.split('').reduce((s, c) => {
let l = s.length-1;
(s[l] && s[l].length < 3) ? s[l] += c : s.push(c);
return s;
}, []);
console.log(output); // output: [ 'abc', 'def', 'ghi', 'jlk', 'm' ]
It works by splitting the string into an array of individual characters, then using Array.reduce to iterate over each character. Normally reduce would return a single value, but in this case the single value happens to be an array, and as we pass over each character we append it to the last item in that array. Once the last item in the array reaches the target length, we append a new array item.
Some clean solution without using regular expressions:
/**
* Create array with maximum chunk length = maxPartSize
* It work safe also for shorter strings than part size
**/
function convertStringToArray(str, maxPartSize){
const chunkArr = [];
let leftStr = str;
do {
chunkArr.push(leftStr.substring(0, maxPartSize));
leftStr = leftStr.substring(maxPartSize, leftStr.length);
} while (leftStr.length > 0);
return chunkArr;
};
Usage example - https://jsfiddle.net/maciejsikora/b6xppj4q/.
I also tried to compare my solution to regexp one which was chosen as right answer. Some test can be found on jsfiddle - https://jsfiddle.net/maciejsikora/2envahrk/. Tests are showing that both methods have similar performance, maybe on first look regexp solution is little bit faster, but judge it Yourself.
var b1 = "";
function myFunction(n) {
if(str.length>=3){
var a = str.substring(0,n);
b1 += a+ "\n"
str = str.substring(n,str.length)
myFunction(n)
}
else{
if(str.length>0){
b1 += str
}
console.log(b1)
}
}
myFunction(4)
function str_split(string, length = 1) {
if (0 >= length)
length = 1;
if (length == 1)
return string.split('');
var string_size = string.length;
var result = [];
for (let i = 0; i < string_size / length; i++)
result[i] = string.substr(i * length, length);
return result;
}
str_split(str, 3)
Benchmark: http://jsben.ch/HkjlU (results differ per browser)
Results (Chrome 104)

Categories