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);
Add a removeLetter function that takes a string and a letter. The result of the function should be string, which does not have the specified character in letter.
How to do peple?
function deleteLetter(string, letter) {
let final = '';
for (let i = 0; i<string.length; i++) {
if (string[i] === letter) {
final.concat(string[i])
}
return final;
}
}
You should return the result at the end of the function, not in the for loop
function deleteLetter(string, letter) {
let final = ""
for (let i = 0; i < string.length; i++) {
if (string[i] !== letter) {
final += string[i]
}
}
return final
}
console.log(deleteLetter("asdasd", "a"))
With ES2021 you'll be able to use String.replaceAll (already available on firefox stable (79) and chrome beta(85)/canary(86))
console.log("test".replaceAll("t", ""))
You can just use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
let str = 'test'
let replaced = str.replace('e', '')
console.log(replaced) // tst
But remember that only first occurrence will be replaced when u use string as first parameter. Use regex solution when you want to remove all of the letters
const removeLetter = (str, letter) =>
str.split('').filter(n => !n.includes(letter)).join('');
console.log(removeLetter('asd', 'a'));
or
const removeLetter = (str, letter) => str.replace(/[^letter]/, '');
console.log(removeLetter('asd', 'a'));
using splice & indexOf
function delLetter(word,letter){
let wordArr = word.split('');
let idx = wordArr.indexOf(letter);
wordArr.splice(idx,1); // deleted here
return wordArr.join('');
}
console.log(delLetter('twinkle','w'))
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");
}
I have this string.
'"pen pineapple" apple pen "pen pen"'
Is there a good way to convert it into an object which would look like this:
{
a: "pen pineapple",
b: "apple",
c: "pen",
d: "pen pen"
}
I am looking for a solution in pure javascript!
Splitting strings that have quotes...
https://stackoverflow.com/a/18647776/2725684
Then converting that array into an object...
https://stackoverflow.com/a/4215753/2725684
So, when you combine these answers, it looks like this...
var myRegexp = /[^\s"]+|"([^"]*)"/gi;
var myString = '"pen pineapple" apple pen "pen pen"';
var myArray = [];
do {
var match = myRegexp.exec(myString);
if (match != null) {
myArray.push(match[1] ? match[1] : match[0]);
}
} while (match != null);
var obj = myArray.reduce(function(acc, cur, i) {
acc[i] = cur;
return acc;
}, {});
console.log(obj);
You could use an adapted version of Split a string by commas but ignore commas within double-quotes using Javascript and use Number#toString method for the keys.
var str = '"pen pineapple" apple pen "pen pen"',
arr = str.match(/(".*?"|[^" \s]+)(?=\s* |\s*$)/g),
object = {};
arr.forEach(function (a, i) {
object[(i + 10).toString(36)] = a.replace(/"/g, '');
})
console.log(object);
This might not be the most efficient function but does what you need (returns array)
function splitter(inputString) {
var splitted = inputString.split(' ');
var out = []
var temp = "";
var quoteStarted = false;
for (i = 0; i < splitted.length; i++) {
if (splitted[i].indexOf('"') > -1 && !quoteStarted) {
temp += splitted[i] + " ";
quoteStarted = true;
} else if (quoteStarted && splitted[i].indexOf('"') == -1) {
temp += splitted[i] + " ";
} else if (quoteStarted && splitted[i].indexOf('"') > -1) {
temp += splitted[i];
out.push(temp);
quoteStarted = false;
temp = "";
} else {
out.push(splitted[i])
}
}
return out;
}
It can be achieved in pure javascript like this way
let str = '"pen pineapple" "apple" "pen" "pen pen"'
let obj = {}
let pattern = /".*?"/g;
let index = ["a","b","c","d","e"]
let i=0
let key
while(current = pattern.exec(str))
{
key = index[i]
obj[key] = current[0].replace('"','')
i++
}
console.log(obj)
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)