I'm trying to write a JS code that will split a sentence into an array of elements, but without all the special characters (like commas, dots, exclamation and question marks etc.). But when I try to display the list of all the elements, there are empty lines. How do I get rid of that?
Here's my code:
function Splitter() {
var sentence = "Here is a sentence, with commas and with other characters, such as dots. And numbers 123 45 6!?";
var chars = [' ', '\\\+', '-', '\\\(', '\\\)', '\\*', '/', ':', '\\\?', '!', '\\\,', '\\\.'];
var parts = sentence.trim().split(new RegExp(chars.join('|'), 'g'));
var longestIndex = -1;
var longestWord = 0;
for(var i=0; i < parts.length; i++){
if(parts[i].length > longestWord){
longestWord = parts[i].length;
longestIndex = i;
}
}
document.write("<b>Original sentence:</b><br>" + sentence);
document.write("<br><br><b>how many words in sentence:</b> " + parts.length);
document.write("<br><br><b>the longest word is:</b> " + parts[longestIndex] + "<br>(number of characters in this word: " + longestWord + ")");
document.write("<br><br><b>fifth word:</b> " + parts[4]);
document.write("<br><br><b>words:</b><br><ol>");
for(var k=0; k<parts.length; k++) {
document.write("<li>" + parts[k] + "</li>");
}
document.write("</ol>");
}
Splitter();
It counts words, and shows the longest word, but when it comes to display all the elements, the result shows empty lines (where comma, or exclamation mark are in the original sentence). The "fifth word" also shows empty value.
What am I doing wrong here?