This question already has answers here:
Why does this code not only count vowels? [duplicate]
(3 answers)
Closed 7 years ago.
I need to debug this segment of code for a class and I have fixed a number of things but I'm not sure why it doesnt work. It is supposed to count the number of vowels in the phrase and return them in the div element i believe. However it always returns "undefined vowels"
Here is the html
<!doctype html>
<html>
<!-- vowels.html -->
<head>
<meta charset="utf-8">
<title>Vowels</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="vowels.js"></script>
</head>
<body>
<header>
<h1>I'd like to buy a vowel</h1>
</header>
<main>
<label>
Type a phrase here:
<input type='text' id='textBox'> </input>
</label>
<button id='countBtn' type='button'> <!--changed countButton to countBtn-->
Count Vowels (a,e,i,o,u)
</button>
<div id='outputDiv'>
</div>
</main>
<footer>
<hr>
<p>© UO CIS 111 2015 April™ LLC</p>
</footer>
</body>
</html>
and here is my JS
function countVowels() {
var textBox, phrase, i, pLength, letter, vowelCount; //removed alert count vowels
textBox = document.getElementById('textBox'); //corrected spelling of Element
phrase = textBox.value;
phrase = phrase.toLowerCase; //switched to lower case
for(i = 0; i < phrase.length; i+= 1) {
letter = phrase[i];
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') { //fixed the spelling of letter. added another = in letter = 'e'
vowelCount = vowelCount + 1;
}
}
alert(vowelCount + ' vowels');
var outArea = document.getElementById('outputDiv'); //corrected to outputDiv instead of outputId and put document. in front of the getElement
outArea.innerHTML = vowelCount + ' vowels in ' + phrase;
}
function init(){
alert('init vowels');
var countTag = document.getElementById('countBtn'); //switched to semi- colon and condensed to single line
countTag.onclick = countVowels;
}
window.onload = init;
Here is a JSFiddle
You can also use RegExp for slimmer code: http://jsfiddle.net/4o67u3js/
HTML:
<p id = "text">
Lorem ipsum dolor sit amet.
</p>
<p id = "result"># of vowels: <span></span></p>
JS:
$(function() {
var vowelsCount = $("#text").text().match(/[aeiou]/gi).length;
$("#result > span").html(vowelsCount);
});
Here's a more algorithmic solution. And, yes it defines a function on the prototype and those who are opposed to that practice can rewrite the function imperatively.
Plain JS:
var str = "Lorem ipsum dolor sit amet.";
String.prototype.vowelsCount = function() {
var str = this.toLowerCase(),
len = str.length,
index = 0,
vowels = ["a", "e", "i", "o", "u"],
count = 0;
for( ; index < len; vowels.indexOf(str[index++]) !== -1 ? count++ : count);
return count;
};
console.log(str.vowelsCount());
The first thing you need to do is make sure you're initializing your init() function on window load. Change window.onload = init; to window.onload = init().
Next, change your double-equals to a triple-equals. It's generally good practice to do so:
if (letter === 'a' || letter === 'e' || letter === 'i' || letter === 'o' || letter === 'u')
Then, to get your counter working, you need to call toLowerCase() in phrase = phrase.toLowerCase. It should look like this: phrase = phrase.toLowerCase()
Here is your fixed JS code:
function countVowels() {
var textBox, phrase, i, pLength, letter, vowelCount; //removed alert count vowels
textBox = document.getElementById('textBox'); //corrected spelling of Element
phrase = textBox.value;
phrase = phrase.toLowerCase(); //switched to lower case
vowelCount = 0;
for(i = 0; i < phrase.length; i+= 1) {
letter = phrase[i];
if (letter === 'a' || letter === 'e' || letter === 'i' || letter === 'o' || letter === 'u') { //fixed the spelling of letter. added another = in letter = 'e'
vowelCount++;
}
}
alert(vowelCount + ' vowels');
var outArea = document.getElementById('outputDiv'); //corrected to outputDiv instead of outputId and put document. in front of the getElement
outArea.innerHTML = vowelCount + ' vowels in ' + phrase;
}
function init(){
alert('init vowels');
var countTag = document.getElementById('countBtn'); //switched to semi- colon and condensed to single line
countTag.onclick = countVowels;
}
window.onload = init();
Related
i am new in javascript.
I have below code where textarea contains text as...
<textarea id="myBox" >
{Picker:} Helper
This is just demo...
</textarea>
<br/>
<span id="ans"></span> <br/>
<input type="button" onclick="getWord()" value="Click"/>
i am trying to find out the word exact after the {Picker:}, i.e. i want to find word "Helper". So word {Picker:} is the point from where i am starting to find immediate word after it. For this i using indexOf. What i did uptil now is ...
<script>
function getWord() {
var val = $("#myBox").val();
var myString = val.substr((val.indexOf("{Picker:}")) + parseInt(10), parseInt(val.indexOf(' ')) );
$("#ans").text(myString);
}
</script>
will anyone guide me to find what mistake i am making. Thanks in advance.
You should start from the index of "{Picker:}" + 9, because the length of the particular string is 9.
Parse till the the index of '\n' which is the line break character.
String.prototype.substr() is deprecated, use String.prototype.substring() instead.
function getWord() {
var val = $("#myBox").val();
var myString = val.substring((val.indexOf("{Picker:}")) + 9, val.indexOf('\n'));
$("#ans").text(myString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<textarea id="myBox">
{Picker:} Helper
This is just demo...
</textarea>
<br />
<span id="ans"></span> <br />
<input type="button" onclick="getWord()" value="Click" />
var val = $("#myBox").val();
console.log(val)
var tempArray = val.replace("\n", " ").split(" ");
var wordToFind;
for(var i = 0 ; i < tempArray.length; i++) {
var word = tempArray[i];
if (word == "{Picker:}") {
wordToFind = tempArray[i + 1]
}
}
console.log(wordToFind)
This will assign what ever word comes after Picker: to the wordToFind variable.
Check working :https://jsfiddle.net/o5qasnd0/14/
You could do something like this
const text = "{Picker:} Helper";
const wordArr = text.split(' ');
const idx = wordArr.indexOf('{Picker:}');
console.log(idx != -1 && (idx + 1) < wordArr.length ? wordArr[idx + 1] : 'not found');
1) I'm trying to apply the first letter in uppercase and the other as lowercase. If the user write in the input, it should automatically transform. Examples:
"isaac guilherme araújo" to "Isaac Guilherme Araújo"
"iSAAC guILHErme aRAÚJO" to "Isaac Guilherme Araújo"
2) In Brazil there are names with connectives.
Examples: "das" "da" "dos" "do" "de" "e".
Carlos Eduardo Julio dos Santos
Carlos Eduardo dos Santos e Silva
Carlos Eduardo da Silva
3) I am having this problem to work with the name fields. With the following code, i could apply the first letter in uppercase, but the others as lowercase i couldn't. Then, according to problem number 2, if I write:
value entered: "douglas de oliveira júnior"
should be: "Douglas de Oliveira Júnior"
shouldn't: "douglas de Oliveira Júnior". //value shown with current code
function contains(str, search){
if(str.indexOf(search) >= 0){
return true;
} else {
return false;
}
}
$.fn.capitalize = function(str) {
$.each(this, function() {
var split = this.value.split(' ');
for (var i = 0, len = split.length; i < len; i++) {
var verify = (split[len - 1] == "D" || split[len - 1] == "d") && (str == "e" || str == "E") || (str == "o" || str == "O");
if (verify == false) {
if ( contains(split[i], 'de') == false && contains(split[i], 'do') == false) {
split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
}
}
}
this.value = split.join(' ');
});
return this;
};
$(".capitalize").keypress(function(e) {
var str = String.fromCharCode(e.which);
$(this).capitalize(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Nome: </label>
<input type="text" id="nome" name="nome" class="form-control input-sm capitalize">
I'm a new member here on Stackoverflow and I apologize for the mistakes, I am learning javascript. Thank you!
This solution also fixes connectives in uppercase, such as carlos DE silva.
Try it with the snippet below :)
var connectives = {
das: true,
da: true,
dos: true,
do: true,
de: true,
e: true
};
function capitalize(str) {
return str
.split(" ")
.map(function(word) {
return !connectives[word.toLowerCase()]
? word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
: word.toLowerCase();
})
.join(" ");
};
$(".capitalize").keyup(function() {
var cursorStart = this.selectionStart;
var cursorEnd = this.selectionEnd;
var capitalizedString = capitalize($(this).val());
$(this).val(capitalizedString);
this.setSelectionRange(cursorStart, cursorEnd);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Nome: </label>
<input type="text" id="nome" name="nome" class="form-control input-sm capitalize">
You could use a format function that capitalizes all words except those provided in a whitelist. Then format the input value whenever the user presses a key (doesn't work well if the user moves the input cursor around though):
function format(string, noCapList=[]) {
const words = string.toLowerCase().split(' ');
return words.map((word) => {
if(!word.length || noCapList.includes(word)) {
return word;
} else {
return word[0].toUpperCase() + word.slice(1);
}
}).join(' ');
}
const input = document.querySelector('input');
input.addEventListener('keyup', () => {
input.value = format(input.value, ["das", "da", "dos", "do", "de", "e"]);
});
<input/>
It looks like the issue with your code is in how you're formatting the input. I'm not 100% sure I understood the question, but this format function provides the output you were looking for.
for simplicity I used npm lodash
https://lodash.com/docs/4.17.11#capitalize
const _ = require('lodash');
const connectives = {
das: true,
da: true,
dos: true,
do: true,
de: true,
e: true
};
const nameToCapitalize = str.split(' ').map(word => connectives[word] ?
word.toLowercase : _.capitalize(word)).join(' ');
SimpleJ's answer is right, but to clarify your original approach: the "problem" is in the contains function - it actually does what it should according to it's name and returns true if the str contains search, so contains('douglas', 'do') === true; you already have the string split into separate words so just use split[i] !== "de" && split[i] !== "do" instead of the contains calls.
I have posted algorithm in FCC about title casing a sentence . Might it would help you!
function titleCase(str) {
//First Converted to lowercase in case of test cases are tricky ones
var spl=str.toLowerCase();
//Then Splitted in one word format as leaving one space as ' '
spl = spl.split(' ');
for(var i=0;i<spl.length;i++){
//Again Splitting done to split one letter from that respective word
var spl2= spl[i].split('');
// In specific word's letter looping has to be done in order to
// convert 0th index character to uppercase
for(var j=0;j<spl2.length;j++){
spl2[0]= spl2[0].toUpperCase();
}
// Then Joined Those letters to form into word again
spl[i] = spl2.join('');
}
// Then joined those words to form string
str = spl.join(' ');
return str;
}
titleCase("sHoRt AnD sToUt");
I found something that apparently was satisfactory. It even works when the user places the cursor in the middle of the input. I found it here:
Link - Stackoverflow
Can anyone here evaluate and tell me if have some problem with this code from the user Doglas?
function ucfirst (str) {
// discuss at: http://locutus.io/php/ucfirst/
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
var not_capitalize = ['de', 'da', 'do', 'das', 'dos', 'e'];
$.fn.maskOwnName = function(pos) {
$(this).keypress(function(e){
if(e.altKey || e.ctrlKey)
return;
var new_char = String.fromCharCode(e.which).toLowerCase();
if(/[a-zà-ú\.\, ]/.test(new_char) || e.keyCode == 8){
var start = this.selectionStart, end = this.selectionEnd;
if(e.keyCode == 8){
if(start == end)
start--;
new_char = '';
}
var new_value = [this.value.slice(0, start), new_char, this.value.slice(end)].join('');
var maxlength = this.getAttribute('maxlength');
var words = new_value.split(' ');
start += new_char.length;
end = start;
if(maxlength === null || new_value.length <= maxlength)
e.preventDefault();
else
return;
for (var i = 0; i < words.length; i++){
words[i] = words[i].toLowerCase();
if(not_capitalize.indexOf(words[i]) == -1)
words[i] = ucfirst(words[i]);
}
this.value = words.join(' ');
this.setSelectionRange(start, end);
}
});
$.fn.maskLowerName = function(pos) {
$(this).css('text-transform', 'lowercase').bind('blur change', function(){
this.value = this.value.toLowerCase();
});
};
$.fn.maskUpperName = function(pos) {
$(this).css('text-transform', 'uppercase').bind('blur change', function(){
this.value = this.value.toUpperCase();
});
};
};
$('.capitalize').maskOwnName();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Nome: </label>
<input type="text" id="nome" name="nome" class="form-control input-sm capitalize">
This question already has answers here:
Check if string inside an array javascript
(2 answers)
Closed 5 years ago.
I'm trying to check if the inputted word is already inside of my array. SO for example, if someone enters 'cat' more than once an error message will display saying "cat has already been entered". I've tried a few different combinations of code but nothing I do seems to work. The findword function is what I have so far. Can someone take a look at my code and explain why its not working and provide a possible fix.
On another note, why doesn't the "word: empty" message pop up when the input field has been left blank?.
<body>
<input type="text" id=input></input>
<button onclick="addword()" class="button" type = "button">Add word</button><br><br>
<button onclick="start()" class="button" type = "button">Process word</button><br><br>
<p id="ErrorOutput"></p>
<p id="output"></p>
<p id="nameExists"></p>
</body>
.
var array = [];
return = document.getElementById("input").value;
function start() {
var word = "word List";
var i = array.length
if (word.trim() === "") {
word = "word: Empty"
}
document.getElementById('ErrorOutput').innerHTML = word
while (i--) {
document.getElementById('output').innerHTML = array[i] + "<br/>" + document.getElementById('output').innerHTML;
}
var longestWord = {
longword: '',len: 0};
array.forEach(w => {
if (longestWord.len < w.length) {
longestWord.text = w;
longestWord.len = w.length;
}
});
document.getElementById('ErrorOutput').innerHTML = "The longest name in the array is " + longestWord.len + " characters";
}
function addword() {
return = document.getElementById('input').value;
array.push(return);
}
function findword() {
var nameExists = array.indexOf(
return) < 0 ?
'The number ' +
return +' does not exist in the array': 'The number ' +
return +' exists in the array'
document.getElementById('nameExists').textContent = nameExists
}
You can use array.indexOf(word) (command for your situation) to find the position of the word.
If the position is -1 the word is not inside the array.
More information on W3
I have an array in javascript like that :
var books = ['spring','last night','sweet heart','the sky','tomorrow'] ;
I have textarea
<textarea id="text" name="textpreview" class="text"></textarea>
So what I want is when I enter letter s then I will get two suggestions books just the first word not the second word I mean not sky Just spring and sweet heart .
I will get two spans
<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
<span>sweet heart</span>
If I type again after s the p letter like sp in textarea then I will get just spring
<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
and so on .
If I type n I will get nothing.
If I type t I will get tomorrow and the sky
Hope it can be done . Thanks for your support .
This help you :
<html>
<head>
<title></title>
</head>
<body>
<textarea id="text" name="textpreview" class="text"></textarea>
<p id="x"></p>
<script>
var x = document.getElementById("x");
var books = ['spring','last night','sweet heart','last night','the sky','tomorrow','tomorrow'];
var txt = document.getElementById("text");
txt.onkeyup = function(event) {
var str = "";
var arr = [];
var index = (txt.value).indexOf("#");
if(index !== -1 && (txt.value).substr(index + 1).length > 0) {
var value = (txt.value).substr(index + 1);
value = value.replace(/[\.\+\*\\\?]/g,'\\$&');
var patt = new RegExp("^" + value);
for(var i=0; i<books.length; i++) {
if(patt.test(books[i]) && arr.indexOf(books[i]) === -1) {
arr.push(books[i]);
}
}
}
if (arr.length < 1 )
x.innerHTML = "";
else {
for(var i=0; i<arr.length; i++)
str+=arr[i]+"<br>";
x.innerHTML = str;
}
}
</script>
</body>
</html>
This problem consists of two parts: Reading and writing your input/output from/to the DOM, and filtering your array books.
The reading and writing part should be easy, there are plenty of guides on how to achieve this.
To filter the books array, JavaScript offers a number of helpful functions:
var books = ['spring','last night','sweet heart','the sky','tomorrow'];
var input = 'S';
var result = books.filter(function(book) {
return book.toLowerCase().indexOf(input.toLowerCase()) === 0;
}).slice(0, 2);
console.log(result); // ['spring', 'sweet heart']
#TimoSta is correct that this is a two-part problem.
I expanded on his code a bit using angular to display the results in the DOM.
http://jsfiddle.net/kcmg9cae/
HTML:
<div ng-controller="MyCtrl">
<textarea id="text" name="textpreview" class="text" ng-model="startsWith"></textarea>
<span ng-repeat="book in sortedBooks()">{{ book }}</span>
</div>
Javascript:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.books = ['spring','last night','sweet heart','the sky','tomorrow'];
$scope.sortedBooks = function () {
var sortedBooks = [];
for (var i = 0; i < $scope.books.length; i++){
if ($scope.books[i].toLowerCase().indexOf($scope.startsWith.toLowerCase()) === 0)
sortedBooks.push($scope.books[i]);
}
return sortedBooks;
}
}
I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}