Nachiket Deolankar Nachiket Deolankar - 7 months ago 40
Javascript Question

Java Script Sentence Break Down

I want to break down a sentence like "Hello World!, Java Script is a best Scripting Language" into a each word I would have to convert the sentence into an array. Right?? And secondly if I want to break down those words in the array into letters then what do I have to do? Meaning I want "Hello World!" to be broke down into "H, e, l, l, o" & "w,o,r,l,d!".

Answer

String.prototype.split():

If you want the punctuation, instead of using .split(/W+/g), use .split(' ') instead.

var str =  "Hello World!, Java Script is a best Scripting Language";

document.body.insertAdjacentHTML('beforeend', str.split(/\W+/g) + '<br>');
document.body.insertAdjacentHTML('beforeend', str.split(/\W+/g).map(function(word) {
  return word.split('');
}));