Related
I want to extract the variables names from a string like this: "foo=valor bar=second", and so on.
To return:
{
foo: "valor",
bar: "second",
...
}
You can use Regex Look Aheads to check for a variable name that is preceded by an = symbol
var str = "foo=valor bar=second";
var varRegex = /\w+(?=(\s)*(\=))/g;
var valueRegex = /(?<=(\=)[\s'"]*)\w+/g;
var varArr = str.match(varRegex);
var valueArr = str.match(valueRegex);
console.log(valueArr);
let obj = {};
for(let i in varArr) {
obj[varArr[i]] = valueArr[i];
}
console.log(obj);
var str = "foo=valor,bar=second";
var obj = {};
str.split(",").forEach(
function(item){
if(item){
var vars = item.split("=");
obj[vars[0]] = vars[1]
}
});
console.log(obj)
Different approach from the previous answer: You can split the string on spaces and then map the result array, splitting on the equal sign to create your object (left side is property, right side is value)
If you need it your specific format you can reduce it to convert the array into one big object with all the values
let a = "foo=valor bar=second"
console.log(a.split(' ').map((i,v) => { return JSON.parse(`{"${i.split('=')[0]}": "${i.split('=')[1]}"}`);}))
let b = a.split(' ').map((i,v) => { return JSON.parse(`{"${i.split('=')[0]}": "${i.split('=')[1]}"}`);})
console.log(b.reduce(function(acc, x) {
for (var key in x) acc[key] = x[key];
return acc;
}));
Not necessarily the quickest answer (in terms of speed of submission), but less regular expressions to maintain and less variables to store.
function toJSON(str) {
const regex = /(\w+)\=(\w+)\s*/g;
let result = {};
let match;
while (match = regex.exec(str)) {
result[match[1]] = match[2];
}
return result;
}
console.log(toJSON("foo=valor bar=second"));
Input Array:
["a,b,c", "foo,bar", "1,2,1", "a"] // should convert to → '"a,b,c","foo,bar","1,2,1","a"'
Now, using toString() or .join("") will produce the unwanted:
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
console.log( arr.toString() )
console.log( arr.join(',') )
So, to bypass that, the first which comes to mind is JSON.stringify:
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
var s = JSON.stringify(arr).slice(1,-1);
console.log( typeof s, ":" , s )
↑ The above is the wanted result, but i'm sure there's a cleaner way of doing it
Question:
Is this the only way to convert an Array which has string items containing commas to a String?
Here is another way to get the same result as with stringify (except when arr contains strings with embedded double-quotes):
arr.reduce((a, c, i) => a + (i > 0 ? ',"' : '"') + c + '"', '')
It depends on what "converting to string" means to you. An array is an ordered list of items numerically accessed. A string is a textual representation of that ordered list. If your question is "how to convert an array to a string while still being able to get the original array back," then the most performant answer would be JSON.stringify to convert the Array to a String, then JSON.parse to convert the string back into an array. However, JSON.stringify is only one of the many ways you could convert an array to a string.
A simple way to join all the strings in the array together is either by using Array.prototype.join.call or String.prototype.concat.apply
"use strict";
(function(){
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
console.log( "Array.prototype.join: ", arr.join("") );
console.log( "String.prototype.concat: ", String.prototype.concat.apply("", arr) );
})();
Another way you could convert an array to a string is by going through each string in the array and concatenating them together.
"use strict";
(function(){
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
var res = "";
var i = arr.length;
var curStr = "";
while (i--) {
curStr = arr[i];
// when the item on the left side is a string, the "+"
// operator acts as a concatination operator
res = res + curStr + ",";
// res += curStr + ","; // works just as well
// res += arr[i] + ","; // also works too
}
console.log( res );
})();
Using the fact that we can go through each item in the array, and look at each string individually, we can do something like converting each string to a base64 blob, then joining each string with a line break.
"use strict";
(function(window){
var btoa = window.btoa, atob = window.atob;
function encode(theArray){
var i = theArray.length, res = "";
while (i--) res += btoa(theArray[i]) + "\n";
return res.slice(0,-1);
}
function decode(theString){
var splitted = theString.split("\n");
var i = splitted.length, res = [];
while (i--) res.push( atob(splitted[i]) );
return res;
}
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
var encoded_arr = encode(arr);
console.log("encoded_arr: ", JSON.stringify(encoded_arr, null, 1).replace(/\\n/g, "\n") );
var decoded_arr = decode(encoded_arr);
console.log( "decoded_arr", JSON.stringify(decoded_arr, null, 1).replace(/\\n/g, "\n") );
})(self);
There are countless more ways to join an array of strings together depending on your specific needs. Below are many such examples. Please emphasize that while all the following "work", none of them are as efficient as Array.prototype.join.
String.prototype.replace
function joinWithRegexp(str1, str2) {
return str1.replace(new RegExp("$"), str2);
}
console.log(joinWithRegexp("Foo", " bar"));
String.prototype.padStart
function joinWithPadStart(str1, str2) {
return str2.padStart(str1.length + str2.length, str1);
}
console.log(joinWithPadStart("Foo", " bar"));
String.prototype.padEnd
function joinWithPadEnd(str1, str2) {
return str1.padEnd(str1.length + str2.length, str2);
}
console.log(joinWithPadEnd("Foo", " bar"));
Template Literals
function joinWithTemplateLiteral(str1, str2) {
return `${str1}${str2}`;
}
console.log(joinWithTemplateLiteral("Foo", " bar"));
DOM
var tmpElement = document.createElement("div");
function joinWithDOM(str1, str2) {
tmpElement.appendChild(document.createTextNode(str1));
tmpElement.appendChild(document.createTextNode(str2));
return tmpElement.textContent;
}
console.log(joinWithDOM("Foo", " bar"));
Blob
var reader = new FileReader;
function joinWithBlob(str1, str2, thenFunc) {
reader.onload = function(){ thenFunc( reader.result ); };
reader.readAsText(new Blob([str1, str2]));
}
joinWithBlob("Foo", " bar", function(result){
console.log(result);
});
I want to merge two variable with stings alternately using javascript. What would be an algorithm to accomplish this task?
For example:
var a = "abc"
var b = "def"
result = "adbecf"
I would use Array.from to generate an array from the strings (unicode conscious).
After that, just add a letter from each string until there's no letters left in each. Please note this solution will combine strings of uneven length (aa+bbbb=ababbb)
var a = "abc"
var b = "def"
var d = "foo 𝌆 bar mañana mañana"
function combineStrings(a,b){
var c = "";
a = Array.from(a);
b = Array.from(b);
while(a.length > 0 || b.length > 0){
if(a.length > 0)
c += a.splice(0,1);
if(b.length > 0)
c += b.splice(0,1);
}
return c;
}
var test = combineStrings(a,b);
console.log(test);
var test2 = combineStrings(a,d);
console.log(test2);
The best way to do this is to perform the following algorithm:
Iterate through string 1
For each character, if there is a character in the same position in string 2, replace the original character with both
This can be achieved with the following code:
function merge(s, t) {
return s.split("")
.map(function(v,i) {
return t[i] ? v + t[i] : v
})
.join("")
}
or the more Codegolf type answer:
s=>t=>[...s].map((v,i)=>t[i]?v+t[i]:v).join``
The simple way would be define the longest string and assigned to for loop. Also you have to add if statments for strings of uneven length, because you want to ignore undefined values of shorter string.
function mergeStrings(s1, s2){
var n = s1.length;
if(s1.length < s2.length){
n = s2.length;
}
var string = '';
for(var i = 0; i < n; i++){
if(s1[i]){
string += s1[i];
}
if(s2[i]){
string += s2[i];
}
}
return string;
}
console.log(mergeStrings('ab','lmnap'));
console.log(mergeStrings('abc','def'));
If your strings are the same length, this will work. If not you'll have to append the rest of the longer string after the loop. You can declare i outside of the loop and then use substr() to get the end of the longer string.
const a = "abc"
const b = "def"
var res = "";
for (var i = 0;i < Math.min(a.length, b.length); i++) {
res += a.charAt(i) + b.charAt(i)
}
console.log(res)
Regex or array processing and joining do the job:
let a = 'abc';
let b = 'def';
console.log(a.replace(/./g, (c, i) => c + b[i])); // 'adbecf'
console.log(Array.from(a, (c, i) => c + b[i]).join('')); // 'adbecf'
You can solve this using array spread and reduce. Split each string into an array and merge into one array and then use reduce to generate the merged string.
function mergeStrings(a, b) {
const mergedValues = [
...a.split(''),
...b.split('')
].reduce((values, currentValue) => {
if (!values.includes(currentValue)) {
values.push(currentValue);
}
return values;
}, []);
return Array.from(mergedValues).join('');
}
I am trying to parse this string into a organized set of functions:
var str = "a(b, c(e, f(h,i,j), g(k,l,m(o,p,q)) ), d(r,s,t))"
Ideally I would like to turn it into an object like this:
var obj = {
func:'a',
params:[
{p:'b'},
{p: {
func:'c',
params:[
{
p:'e',
p:{
func:'f',
params:[
{p:'h'},
{p:'i'},
{p:'j'}
]
},
p:'g',
params:[
{p:'k'},
{p:'l'},
{p:{
func:'m',
params:[
{p:'o'},
{p:'p'},
{p:'q'}
]
}}
]
}
]
}},
{
p:'d',
params:[
{p:'r'},
{p:'s'},
{p:'t'}
]
}
]
}
I have tried about 8 hours of mixed str.replace() str.substring(), and str.indexOf() and not had any luck.
Any help about how to go about achieving my goal would be appreocated.
note: the functions could take any number params and is not set to 3
UPDATE -- I stopped trying to do string manipulation and approached it character by character. To create desired output:
var str = "a(b, c(e, f(h,i,j), g(k,l,m(o,p,q)) ), d(r,s,t))";
str = str.replace('/ /g,""');
var strArr = str.split('');
var firstPass = "";
var final;
var buildObj = function(){
for(var i = 0; i < strArr.length; i++){
var letters = /^[0-9a-zA-Z]+$/;
if(strArr[i].match(letters)){
if(strArr[i + 1] == '('){
firstPass += '},{"func":' + '"' + strArr[i] + '"';
} else {
firstPass += '"' + strArr[i] + '"';
}
}
if(strArr[i] == '('){
firstPass += ',"params":[{"p":';
}
if(strArr[i] == ')'){
firstPass += '}],';
}
if(strArr[i] == ','){
firstPass += '},{"p":';
}
//console.log(job + '}')
}
var secondPass = firstPass;
secondPass += '}'
secondPass = secondPass.replace(/,{"p":}/g,'');
secondPass = secondPass.replace('},','');
secondPass = secondPass.replace(/],}/g,']}');
final = secondPass
console.log(final)
console.log(JSON.parse(final))
};
Regular expressions and string hacking isn't going to work; regexes cannot handle (directly) any text with nested structures (people keep learning this...). Switching to single characters doesn't improve anything.
Classically what you want is a lexer that produces tokens (language elements) and a parser (that checks the elements are organized properly).
As a practical matter, you can combine these into one coherent structure for simple languages like the one that interests OP. Check out this SO answer on how to build a recursive descent parser easily; follow that answer to one that tells how to build a tree (in essence, how to build the result structure you want).
I saw the problem, and thought it might be interesting to try. I'll walk through my thought process and hope that helps you.
The object I produce does not entirely map to yours, but could easily be. It was easier to end up with the object I produced without additional work without getting distracted by "extraneous" details like putting things in an array.
1.) I'm assuming whitespace is useless. The first step was to replace all whitespace with nothing.
function processStatement(statement) {
return statement.replace(/[ ]/g, '');
}
// Output: a(b,c(e,f(h,i,j),g(k,l,m(o,p,q))),d(r,s,t))
2.) I proceeded with the goal of creating a tree like object, with parameters that do not lead into more functions as dead ends. I needed a way to parse "roots", the code should explain more:
function produceNodeFromStatement(statement) {
var regex = new RegExp('([a-zA-Z])\\((.+)\\)', 'g');
var results = regex.exec(statement);
// This regex matches for the widest pattern: identifier(stuff-inside)
// Running the previous output would result in matching groups of:
// identifier: a
// stuff-inside: b,c(e,f(h,i,j),g(k,l,m(o,p,q))),d(r,s,t)
var root = {}
// We need a way to split the stuff-inside by commas that are not enclosed in parenthesis.
// We want to turn stuff-inside into the following array:
// [ 'b', 'c(e,f(h,i,j),g(k,l,m(o,p,q)))', 'd(r,s,t)' ]
// Since my regex-fu is bad, I wrote a function to do this, explained in the next step.
var parameters = splitStatementByExternalCommas(results[2]);
var node = {};
parameters.forEach(function (parameter) {
if (parameter.indexOf('(') == -1) {
node[parameter] = null;
} else {
// Recursion. This function produces an anonymous wrapper object around a node.
// I will need to unwrap my result.
var wrappedNode = deconstructStatement(parameter);
var key;
for (key in wrappedNode) {
node[key] = wrappedNode[key];
}
}
});
// Assign node to the node's identifier
root[results[1]] = node;
return root;
}
3.) The only missing piece to the formula is the function that splits a string by only external commas - since I can't figure out a regex, here's splitStatementByExternalCommas.
function splitStatementByExternalCommas(statement) {
statement += ','; // so I don't have to handle the "last, leftover parameter"
var results = [];
var chars = statement.split('');
var level = 0; // levels of parenthesis, used to track how deep I am in ().
var index = 0; // determines which parameter am I currently on.
var temp = '';
// this is somewhat like your implementation in the edits, I walk through the characters one by one, and do something extra if it's a special character.
chars.forEach(function (char) {
switch (char) {
case '(':
temp += char;
level++;
break;
case ')':
temp += char;
level--;
break;
case ',':
// if the comma is between a set of parenthesis, ignore.
if (level !== 0) { temp += char; }
// if the comma is external, split the string.
else { results[index] = temp; temp = ''; index++; }
break;
default:
temp += char;
break;
}
});
return results;
}
4.) Putting everything together, to turn your string statement into an intermediate object:
var str = "a(b, c(e, f(h,i,j), g(k,l,m(o,p,q)) ), d(r,s,t))";
str = processStatement(str);
var root = produceNodeFromStatement(str);
// Output is something like:
{
a: {
b: null,
c: {
e: null,
f: { h: null, i: null, j: null },
g: {
k: null, l: null,
m: { o: null, p: null, q: null }
}
},
d: { r: null, s: null, t: null }
}
}
5.) I'm going to assume mapping this intermediate object to your intended target is straightforward from here on out?
You cannot use the same property name for the 3 values, so you cannot do this.
func:'c',
params:[
{
p:'e',
p:{
func:'f',
params:[
{p:'h'},
{p:'i'},
{p:'j'}
]
},
p:'g',
If we remove this part and fix other inconsistent parts of your example (at least try to write an example which is not a failure on its own), it's relative easy to transform your code into javascript with eval:
parser:
var parse = function (str) {
var compiled = str.replace(/(\w+)\s*(\W)/g, function (match, name, token) {
if (token == "(")
return "q(\"" + name + "\",";
else
return "p(\"" + name + "\")" + token;
}).replace(/,\s*\)/g, ")");
function q(name) {
return {
p: {
func: name,
params: Array.prototype.slice.call(arguments, 1)
}
};
}
function p(name) {
return {
p: name
};
}
var f = eval("(function (){return " + compiled + ";})");
return f().p;
};
test:
describe("x", function () {
it("y", function () {
var str = "a(b, c(e), d(r,s,t))";
var obj = {
func: 'a',
params: [
{p: "b"},
{
p: {
func: 'c',
params: [
{
p: 'e'
}
]
}
},
{
p: {
func: 'd',
params: [
{p: 'r'},
{p: 's'},
{p: 't'}
]
}
}
]
};
expect(parse(str)).toEqual(obj);
});
});
note:
I agree with Ira Baxter, you have to read more about how to do this in general.
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)