How to split an array dynamically on the basis of keywords? - javascript

I have an array(prop1) and also a set of keywords(prop2). I want to be able to split the array as per the keywords so that it looks like the wordSet array. How do I split this? The number of words in prop1 and prop2 can vary.
prop1 = {"Hello World. I want to welcome you to my kingdom"}
prop2 = ['World', 'welcome', 'kingdom']
const wordSet =
[
"Hello ",
"World",
". I want to ",
"welcome",
" you to my ",
"kingdom"
]
arr.map((wordSet) => {
const isHighlighted = prop2.indexOf(wordSet) > -1;
return <span className={isHighlighted ? classes.highlighted : classes.other}>{wordSet}</span>
})

I'd construct a regular expression from the prop2s - make a RE that matches any characters until running into the keywords, and separately capture the matched keyword:
const prop1 = "Hello World. I want to welcome you to my kingdom";
const prop2 = ['World', 'welcome', 'kingdom'];
const pattern = new RegExp('(.*?)($|' + prop2.join('|') + ')', 'gi');
const wordSet = [...prop1.matchAll(pattern)]
.flatMap(m => [m[1], m[2]])
.filter(Boolean);
console.log(wordSet);

I'll do multi pass using split. I am not sure if it will work out well, but let me give a try!
var str = "Hello World. I want to welcome you to my kingdom";
var arr = ['World', 'welcome', 'kingdom'];
var final = [str];
for (var i = 0; i < arr.length; i++) {
final = final.flat(2).map(function (f) {
return f.split(arr[i]).join("aaaa" + arr[i] + "aaaa").split("aaaa");
}).flat(2).filter(a => a);
}
console.log(final);
There could be possibly the aaaa might be a part of the word or the array, that's the only caveat I have got here. But we can switch it using something like this:
var str = "Hello World. I want to welcome you to my kingdom";
var arr = ['World', 'welcome', 'kingdom'];
var final = [str];
for (var i = 0; i < arr.length; i++) {
final = final.flat(2).map(function (f) {
// Not fool proof.
var sep = str.indexOf("aaaa") > -1 ? "bbbb" : "aaaa";
return f.split(arr[i]).join(sep + arr[i] + sep).split(sep);
}).flat(2).filter(a => a);
}
console.log(final);

Related

How to filter input value when a specific value is typed

I need to listen to an input and get its value dynamically,when a specific "flag" happens to be typed,get whatever is typed next until a flag appears again.
let me explain :
lets say i have an array of "flags"
let flags = ['foo','bar','baz']
and i have an input to listen which gives me the following string (dynamically,character by character):
let input = "whateveridontneedthatfoodavidbarjennifer-andrew-billbazericfoojohnbarchristen"
*foo and bar appear twice and baz once
i want somehow to create,maybe an object like this :
{
foo: ["david","john"],
bar: ["jennifer-andrew-bill","christen"],
baz: ["eric"]
}
or 3 separate arrays,i dont really care about the structure as long i filter the value properly
Good answer from #Apple BS, I just want to propose this syntax:
const flags = ['foo', 'bar', 'baz']
const str = 'whateveridontneedthatfoodavidbarjennifer-andrew-billbazericfoojohnbarchristen'
const strSplit = str.split(new RegExp(`(${flags.join('|')})`, 'g'))
const obj = Object.fromEntries(flags.map(f => [f, []]))
strSplit.forEach((el, i) => {
if (flags.includes(el)) obj[el].push(strSplit[i + 1])
})
console.log(obj)
EDIT:
There is an other version using regex capture groups.
const str = 'whateveridontneedthatfoodavidbarjennifer-andrew-billbazericfoojohnbarchristen'
const flags = ['foo', 'bar', 'baz'], flagsJoin = flags.join('|')
const obj = Object.fromEntries(flags.map(f => [f, []]))
const regex = new RegExp(`(${flagsJoin})(.*?)(?=${flagsJoin}|$)`, 'g')
for (const [, flag, sub] of str.matchAll(regex)) obj[flag].push(sub)
console.log(obj)
First, construct a regex:
let regex = '('; // parenthesis is added for capturing groups, which means the flags will be captured too
for (f of flags) regex += f + '|';
regex = new RegExp(regex.substring(0, regex.length - 1) + ')', 'g'); // construct the regex with global flag
// regex = /(foo|bar|baz)/g
Then, split the string:
s = s.split(regex) // ["whateveridontneedthat", "foo", "david", "bar", "jennifer-andrew-bill", "baz", "eric", "foo", "john", "bar", "christen"]
Finally, loop through the splitted string and add them to the object.
Below is the full example:
let flags = ['foo', 'bar', 'baz'];
let s = "whateveridontneedthatfoodavidbarjennifer-andrew-billbazericfoojohnbarchristen";
let regex = '(';
let obj = {};
for (f of flags) regex += f + '|';
regex = new RegExp(regex.substring(0, regex.length - 1) + ')', 'g');
s = s.split(regex);
for (let i = 0; i < s.length; i++) {
for (let j = 0; j < flags.length; j++) { // checking for flags
if (s[i] == flags[j]) { // found the flag
if (flags[j] in obj) obj[flags[j]].push(s[i + 1]); // array exist in object
else obj[flags[j]] = [s[i + 1]]; // create array in object
i++; // skip next s[i]
break; // s[i] can only be one of the flag
}
}
}
console.log(obj);
On top of #AppleBS's and #Jean Will's answer,
Just simplify the for loop.
const flags = ["foo", "bar", "baz"];
const str =
"whateveridontneedthatfoodavidbarjennifer-andrew-billbazericfoojohnbarchristen";
const strSplit = str.split(new RegExp(`(${flags.join("|")})`, "g"));
const output = strSplit.reduce((carry, item, idx, arr) => {
if (idx !== 0) {
if (idx % 2 === 0) carry[arr[idx - 1]].push(item);
else if (!carry[item]) carry[item] = [];
}
return carry;
}, {});
console.log(output);

Determine if string has at least 2 same elements from an array

I want to determine if string has at least 2 same elements from the array
const array = ["!", "?"];
const string1 = "!hello"; // should return false
const string2 = "!hello?"; // should return false
const string3 = "!hello!"; // should return true
const string4 = "hello ??"; // should return true
const string5 = "hello ?test? foo"; // should return true
const string6 = "hello ?test ?? foo"; // should return true
I'm not sure what is gonna be better: a regex or a function? Any would be fine.
I tried this:
const array = ["!", "?"];
const string = "test!";
array.every(ar => !string.includes(ar));
But it only detects if there at least 1 elements from array, not 2.
You can use Array#some and String#split to do it:
const check=(array,string)=>array.some(char=>(string.split(char).length-1)>=2)
const array = ["!", "?"];
console.log(check(array,"!hello"))
console.log(check(array,"!hello?"))
console.log(check(array,"!hello!"))
console.log(check(array,"hello ??"))
console.log(check(array,"hello ?test? foo"))
console.log(check(array, "hello ?test ?? foo"))
How does it work?
Let's split up (I mean to split() up)!
const check=(array,string)=>
array.some(char=>
(
string.split(char)
.length-1
)>=2
)
First, use Array#some, which tests that at least one element of the array should pass (i.e. either ? or !)
Split up the string by char, and count how many parts do we have
If we have n parts, it means that we have n-1 places where the char matches. (e.g. 2 | splits a string into 3 parts: a|b|c)
Finally, test whether we have 2 or more delimiters
Another way is to use a pattern with a capturing group and a dynamically created character class for [!?] and a backreference \1 to what is captured in group 1 to make sure there are 2 of the same characters present.
([!?]).*\1
Regex demo
For example
const array = ["!", "?"];
const regex = new RegExp("([" + array.join(("")) + "]).*\\1");
[
"!hello",
"!hello?",
"!hello!",
"hello ??",
"hello ?test? foo",
"hello ?test ?? foo"
].forEach(str => console.log(str + ": " + regex.test(str)));
You can use string split and array length like:
const array = ["!", "?"];
const string6 = "hello ?test ?? foo";
var len1 = string6.split(array[0]).length;
var len2 = string6.split(array[1]).length;
if (len>2)||(len2>2)
return true;
EDIT: Using for loop
for (let i=0;i<array.length;i++){
var len = string6.split(array[i]).length;
if (len>2)
return true;
}
return false;
You can follow a very simple solution like below. Split the string using the character in array. check the left of the split operation. If the length is minimum 2, then return true, else false.
Here is a sample jsFiddle: https://jsfiddle.net/sagarag05/qk8f2Lz7/
const array = ["!", "?"];
var str = "How are you!! doing !today?";
function isFound(arr, str){
var isPresent = false;
for(var i=0; i < arr.length; i++){
var res = str.split(arr[i]);
if(res.length-1 >= 2){
isPresent = true;
break;
}
}
return isPresent;
}
isFound(array, str);
Create a function which can be handy for n number of occurrences to find
const arrayData = ["!", "?"];
const strData = "test!";
function checkElements(arr, str, occNum) {
var ctr = 0;
arr.forEach(function (elem) { if(str.includes(elem)) ctr++});
return ctr >= occNum
}
checkElements(arrayData, strData, 2)
Use loop over array and count occurrence then check if occurrence is greater than 1.
function has2(string1, array)
{
for(let i=0;i<array.length;i++)
{
if (string1.split('').reduce(function(n, val) {
return n + (val === array[i]);
}, 0) > 1)
{
return true;
}
}
return false;
}
console.log(has2("!hello!", ["!", "?"])); // true
console.log(has2("!hello?", ["!", "?"])); // false
Here is a regex trick approach. We can try removing all characters from the input which are not part of the character class of characters to find. Then, assert that there are at least two distinct characters remaining in the input.
var input = "!hello?";
input = input.replace(/[^!?]+/g, "");
if (/(.).*(?!\1)./.test(input)) {
console.log("MATCH");
}
else {
console.log("NO MATCH");
}
The logic here is fairly straightforward. Using the input !hello? as an example, we first remove all non marker characters, leaving us with !?. Then, we use a regex to assert that there are at least two distinct characters remaining. This is true for this input, so we print MATCH.
Edit:
To build the regex alternation from your input array use join:
const array = ["!", "?"];
var regex = "[^" + array.join("") + "]+";
There is a much simpler solution for this:
var a = ["!", "?"], s = "!hello!";
a.some(v=>s.split(v).length>2) // (returns true if multiples are found)
We can turn it into a function to test:
const a = ["!", "?"];
function Test(s) { return a.some(v => s.split(v).length > 2) }
const string1 = "!hello"; // should return false
const string2 = "!hello?"; // should return false
const string3 = "!hello!"; // should return true
const string4 = "hello ??"; // should return true
const string5 = "hello ?test? foo"; // should return true
const string6 = "hello ?test ?? foo"; // should return true
console.log(Test(string1), Test(string2), Test(string3), Test(string4),
Test(string5), Test(string6));
> false false true true true true
Note: My code changed a few times and in the end was close to the accepted answer and I didn't realize. That said, you don't need to subtract anything, so that part is unnecessary.
function checkDups(arr, str) {
var ctr = [];
for (var i = 0; i < arr.length; i++) {
var pos = str.indexOf(arr[i]);
var count = 0;
ctr[i] = 0;
while (pos > -1) {
++count;
pos = str.indexOf(arr[i], ++pos);
}
if (count >= 2) {
return true
}
}
return false
}
console.log(checkDups(["!", "?"], "!hello"))
console.log(checkDups(["!", "?"], "!hello?"))
console.log(checkDups(["!", "?"], "!hello!"))
console.log(checkDups(["!", "?"], "hello ??"))
console.log(checkDups(["!", "?"], "hello ?test? foo"))
console.log(checkDups(["!", "?"], "hello ?test ?? foo"))

How to count words from window.prompt and sort them by number of apperance?

I need to count words from prompt and write them to the array. Next I have to count their appearance and sort them.
I have code like this:
let a = window.prompt("Write sentence")
a = a.split(" ")
console.log(a)
var i = 0;
for (let i = 0; i < a.length; i++) {
a[i].toUpperCase;
let res = a[i].replace(",", "").replace(".", "")
var count = {};
a.forEach(function(i) {
count[i] = (count[i] || 0) + 1;
});
console.log(count);
document.write(res + "<br>")
}
I don't know how to connect my word with specific number for number of appearances and write this words one time.
On the end it should look like:
a = "This sentence, this stentence, this sentence, nice."
This - 3
Sentence - 3
nice - 1
If I don't misunderstood your requirements then Array.prototype.reduce() and Array.prototype.sort() will the trick for you. Imagine I got the example string from your window.prompt()
let string = `this constructor doesn't have neither a toString nor a valueOf. Both toString and valueOf are missing`;
let array = string.split(' ');
//console.log(array);
let result = array.reduce((obj, word) => {
++obj[word] || (obj[word] = 1); // OR obj[word] = (++obj[word] || 1);
return obj;
}, {});
sorted_result = Object.keys(result).sort(function(a,b){return result[a]-result[b]})
console.log(result);
console.log(sorted_result);
AS PER QUESTION EDIT
let string = `This sentence, this sentence, this sentence, nice.`;
let array = string.split(' ');
array = array.map(v => v.toLowerCase().replace(/[.,\s]/g, ''))
let result = array.reduce((obj, word) => {
++obj[word] || (obj[word] = 1); // OR obj[word] = (++obj[word] || 1);
return obj;
}, {});
console.log(result)
You can use reduce. Like so:
const wordsArray = [...].map(w => w.toLowerCase());
const wordsOcurrenceObj = wordsAray.reduce((acc, word) => {
if (!acc[word]) {
acc[word] = 0;
}
acc[word] += 1;
return acc;
}, {});
What this does is keep track of the words in an object. When a word is not there, initializes with zero. And then adds a 1 every time you encounter that word. You will end up with an object like this:
{
'word': 3,
'other': 1,
...
}
Add another loop at the end that goes over the counts and prints them:
for(let word in count) {
console.log(word + " appeared " + count[word] + " times");
}

Get length of every element in array - JavaScript

I want to get length of every element in array
my code is
var a = "Hello world" ;
var chars = a.split(' ');
so I will have an array of
chars = ['Hello' , 'world'] ;
but how I can get length of each word like this ?
Hello = 5
world = 5
You can use map Array function:
var lengths = chars.map(function(word){
return word.length
})
ES6 is now widely available (2019-10-03) so for completeness — you can use the arrow operator with .map()
var words = [ "Hello", "World", "I", "am", "here" ];
words.map(w => w.length);
> Array [ 5, 5, 1, 2, 4 ]
or, very succinctly
"Hello World I am here".split(' ').map(w => w.length)
> Array [ 5, 5, 1, 2, 4 ]
The key here is to use .length property of a string:
for (var i=0;i<chars.length;i++){
console.log(chars[i].length);
}
You could create a results object (so you have the key, "hello", and the length, 5):
function getLengthOfWords(str) {
var results = {};
var chars = str.split(' ');
chars.forEach(function(item) {
results[item] = item.length;
});
return results;
}
getLengthOfWords("Hello world"); // {'hello': 5, 'world': 5}
Try map()
var words = ['Hello', 'world'];
var lengths = words.map(function(word) {
return word + ' = ' + word.length;
});
console.log(lengths);
You can use forEach, if you want to keep the words, and the length you can do it like this:
var a = "Hello world" ;
var chars = a.split(' ');
var words = [];
chars.forEach(function(str) {
words.push([str, str.length]);
});
You can then access both the size and the word in the array.
Optionally you could have a little POJO object, for easier access:
var a = "Hello world" ;
var chars = a.split(' ');
var words = [];
chars.forEach(function(str) {
words.push({word: str, length: str.length});
});
Then you can access them like:
console.log(words[0].length); //5
console.log(words[0].word); //"Hello"
Or using map to get the same POJO:
var words = chars.map(function(str) {
return {word: str, length: str.length};
});

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