I have a text file (separated by ', '
between each word) and a function that assigns a word a value (where a = 1
, z = 26
) when it is run. (ex: sumChars('JavaScript')
returns 119
.) My question is, how do I get only the first word, run the function with that, and move on to the next word? I know that after using fetch(url)
to get the file, I can use .then(d => d.replace(/\n/, '')).then(d => d.replace("', '", ''))
to get rid of everything else.
Asked
Active
Viewed 101 times
-3

Ethan Slota
- 19
- 8
-
1try to split your string into an array then call your function to each element: `const resp = d.split(', ').map(x => sumChars(x))` – guijob Jan 22 '19 at 23:36
1 Answers
0
The best way to deal with strings in Javascript is to use regular expression, with g (global) flag to process all ocurrences in the string.
var list = [], sums = [];
fetch(url)
.then(txt => list = txt.replace(/\n/g, '').replace(/\s/g, '').split(","); return list;)
.then(res => res.forEach((wrd,idx,arr) => { sums[idx]=0;
wrd.split('').forEach(char => sums[idx] += char.charCodeAt(0)-96)})
);
console.log("result: ", list,sums);
As a reference to get characters value convert characters to ascii code.
As a reference to bind array elements in foreach loop foreach loop by reference.

Yones
- 95
- 7