Task to accomplish: Made a function which counts the amount of words in a sentence.
Please don't put attention to the HTML. Is just for testing-purposes.
var sentence = document.querySelector('#sentence');
var exec = document.querySelector('#exec');
var result = document.querySelector('#result');
// ## THE ACTUAL FUNCTION ###########
// ## Rest is just for testing ######
// Reports the count of words which are
// contained in assigned string.
// Parameter (sentence): Are string is
// expected. The string doesn't have
// to be empty. It has to consist of
// other characters then just blanks.
// Return a number: The count of words
// in the assigned string.
// In case of an error -1 is returned.
function getCountOfWords(sentence) {
if (sentence.length === 0 ||
sentence.search(/\w+/) === -1)
return -1;
if (sentence.search(/\s+/) === -1)
return 1;
return (sentence.match(/(^|\s)\w+/g)).length;
}
// ## END ACTUAL FUNCTION ###########
function execHandler() {
result.value = getCountOfWords(sentence.value);
}
exec.addEventListener('click', execHandler);
.wrap {
margin: 20px auto;
width: 900px;
}
.wrap label {
display: inline-block;
width: 150px;
}
.wrap div {
margin: 20px 0;
}
<div class="wrap">
<div>
<label for="sentence">
Sentence to check:
</label>
<input type="text" id="sentence"
value="one Two2 Three 4four five123"
size="80" />
</div>
<div>
<button id="exec">Exec</button>
</div>
<div>
<label for="sentence">
Count of words:
</label>
<input type="text" id="result" />
</div>
</div>
I have tried to catch everything which could wrong. But perhaps there are cases which I haven't thought about?
Are their better (more elegant) ways to achieve the described task?