Using for loop to find specific characters in string - javascript

I am attempting the bean counting example in the functions chapter of the book Eloquent Javascript. My function is returning a blank.
Without giving me the full answer (I'm working through this example to learn), can someone tell me why my code is not printing any text?"
var string = "donkey puke on me boot thar be thar be!";
for (var i = 0; i <= string.length; i++);
function getB(){
if (string.charAt(i) == "b")
return i;
else return "";
}
console.log(getB());

There is something wrong about how you're trying to implement this feature.
First of all I think it's better if you have a function that accepts the string and the char as parameters in order to call it whenever you want.
Example of calling :
getChar('this is my custom string', 'c') -> it should search character `c` in `this is my custom string`
getChar('this is another custom string', 'b') -> it should search character `b` in `this is another custom string`
Example of implementation :
var getChar = function(string, char){
for(var i=0;i<string.length;i++)
{
if(string.charAt(i)==char) console.log(i);
}
}
Now, try to make it not case-sensitive and instead of console.log the output try to return a sorted array with character positions

Use This,
var string = "donkey puke on me boot thar be thar be!";
for (var i = 0; i <= string.length; i++) {
if (string.charAt(i) == "b") {
console.log(i);
}
}

if you want to print every position your value is at, you can program something like this:
var string = "donkey puke on me boot thar be thar be!";
for (var i = 0; i <= string.length; i++)
{
getChar(i, "b");
}
function getChar(i, input)
{
if (string.charAt(i) == input)
console.log(i);
}

another example: collect all b positions:
var string = "donkey puke on me boot thar be thar be!";
function getB(string){
var placesOfB = [];
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) == "b") {
placesOfB.push(i);
}
}
return placesOfB;
}
console.log(getB(string));

tip: your for has no body (putting ; after it just loops without doing anything)...
and it does not make sense to define a function inside that for.

Without giving you the full answer, I'll just give you pointers:
1. Your for loop is not complete - it doesn't do anything.
2. Your getB() function needs to accept string parameter in order to perform some action on it.
3. The if..else statement doesn't have opening and closing brackets {}

Related

How to count vowels in a Javascript string with two functions?

I'm trying to write a Javascript function that counts the vowels in a string by calling another function inside that function, but when I test it in the console it returns 0.
Here is my first function that works fine and recognizes if a string is a vowel:
function isVowel(ch){
var pattern = /[aeiouAEIOU]/
return pattern.test(ch);
};
For the second function none of my ideas have worked. Here are a few examples of what I have tried so far:
This one returns me a 0:
function countVowels(str){
var count = 0;
for(var i; i <= str.length; ++i){
if(isVowel(i)){
++count;
}
}
return count;
};
I also tried the above, but removing the .length after str in the for() area.
Another example, but this one gives me an error:
function countVowels(str){
var count = 0
var pattern = /[aeiouAEIOU]/
for(var i = 1; i <= str.length(pattern); ++i){
if(isVowel(i)){
++count;
}
}
return count;
};
I've tried various other functions as well, but for the sake of keeping this post relatively short I won't continue to post them. I'm quite new to Javascript and I'm not sure what I'm doing wrong. Any help would be greatly appreciated!
Try using .match() with the g attribute on your String.
g: global
i: case insensitive
Regexp documentation
function countVowels(ch){
return ch.match(/[aeiouy]/gi).length;
}
var str = "My string";
alert(countVowels(str)); // 2
Although Robiseb answer is the way to go, I want to let you know why you code is not working (I'm referring your first attempt). Basically you made two mistakes in the loop:
As CBroe stated, you are passing i to your isVowel function. i is a integer representing the index of the loop, not the actual character inside the string. To get the character you can do str.substr(i, 1), what means "give me one character from the position i inside the string".
You are not giving a initial value to the i variable. When you create a variable, it is undefined, so you can not increment it.
alert(countVowels("hello"));
function countVowels(str) {
var count = 0;
for (var i = 0; i <= str.length; ++i) {
if (isVowel(str.substr(i, 1))) {
count++;
}
}
return count;
};
function isVowel(ch) {
var pattern = /[aeiouAEIOU]/
return pattern.test(ch);
};
UPDATE: You will see that other answers use other methods to select the character inside the string from the index. You actually have a bunch of different options. Just for reference:
str.slice(i,i+1);
str.substring(i,i+1);
str.substr(i,1));
str.charAt(i);
str[i];
i is the index, not the character. It should be:
if (isVowel(str[i])) {
count++;
}
Also, str.length(pattern) is wrong. length is a property, not a function, so it should just be str.length.
You forgot to assign the value 0 to i variable
And parameter for isVowel is the character, not the index of string
Here information about the JS language: https://stackoverflow.com/tags/javascript/info
function isVowel(ch){
var pattern = /[aeiouAEIOU]/
return pattern.test(ch);
}
function countVowels(str){
var count = 0;
// you forgot to assign the value to i variable
for(var i = 0; i < str.length; i++){
// isVowel(str[i]), not isVowel(i)
if(isVowel(str[i])){
count++;
}
}
return count;
}
console.log(countVowels('forgot'))
Obviously you should do it this way:
function isVowel(c){
var lc = c.toLowerCase();
if(lc === 'y'){
return (Math.floor(Math.random() * 2) == 0);
}
return ['a','e','i','o','u'].indexOf(lc) > -1;
}
function countVowels(s){
var i = 0;
s.split('').each(function(c){
if(isVowel(c)){
i++;
}
});
return i;
}
console.log(countVowels("the quick brown fox jumps over the lazy dog"));
Which, although less efficient and less useful than other answers, at least has the entertaining property of returning a different count 50% of the time, because sometimes Y.

String permutation from Java to Javascript

I am new to Javascript and I was trying to reproduce a Java string permutation using Javascript but I cannot get the correct result.
Note: I followed this algorithm here (Hemant's answer): String permutation with recursion
Here is my code:
function getAllPermutations(input){
var permutations = [];
function loop(prefix, input){
var len = input.length;
if(len==0) {
permutations.push(prefix);
}
else{
for(i = 0; i < len; i++){
loop(prefix + input.charAt(i),input.substr(0,i) + input.substr(i+1,len));
}
}
}
loop("", input);
return permutations;
}
When I call getAllPermutations("good"), it's only returning ["good"]. What's going on with this code? Am I missing anything about the call back scope?
The problem is that the variable i in the for loop is defined globally. Therefore in each recursion the variable retains the value of the former iteration.
It can be fixed by writing var in front of the variable to make it a local variable like in the following code snippet.
for(var i = 0; i < len; i++){
// ...
}

Best way to create string filter comparation?

My goal's create a filter search function, in particular actually I'm using .indexOf method that allow me to check if two string are equal. The problem's that if I've the compare string with space break like this: Hair Cut.
Example:
String to search: Hair
String contained in the object: Hair Cut
var cerca = $('#filter_service').val();
for(var i = 0; i < GlobalVariables.availableServices.length; i++) {
if (cerca.toLowerCase().contains(GlobalVariables.availableServices[i].name.toLowerCase()) != -1) {
console.log(GlobalVariables.availableServices[i].name)
}
}
How you can see I valorize the variable cerca that contains the string Hair in the example. I compare this with an object variable, how I said, the problem is if I insert the string Hair I get no response in console, also if I insert the string with break space like the compare string Hair Cut I get the console response.
How I can print a result also when the variable cerca is equal to the first character of the compair string? In particular Hai?
I don't know if I was clear, hope yes.
.contains() is for checking DOM element children. You said above that you are using .indexOf to check, but it doesn't look like you use it in your code?
var cerca = $('#filter_service').val();
var searchIn;
for(var i = 0; i < GlobalVariables.availableServices.length; i++) {
searchIn = GlobalVariables.availableServices[i].name.toLowerCase().split(' ');
for (j = 0; j < searchIn.length; j++) {
if (cerca.toLowerCase().split(' ').indexOf(searchIn[j].toLowerCase()) >= 0) {
console.log(GlobalVariables.availableServices[i].name);
}
}
}
$('#filter_service').on('input', function() {
var inputStr = $('#filter_service').val();
var similar = [];
for (i = 0; i < GlobalVariables.availableServices.length; i++) {
if (GlobalVariables.availableServices[i].name.toLowerCase().indexOf(inputStr.toLowerCase) >= 0) {
similar[similar.length] = GlobalVariables.availableServices[i].name;
}
}
// At this point, you can do whatever you want with the similar service
// names (all of the possible result names are included in the array, similar[].)
});
I can't test that code right now, but in theory, it should work.
Here is a JSFiddle demo:
http://jsfiddle.net/MrGarretto/vrp5pghr/
EDIT: Updated and fixed my errors
EDIT 2: Added the 'possible results' solution
EDIT 3: Added a JSFiddle

Use toSentenceCase on function parameter Javascript

In a Codecademy assignment, I would like to add a case to the parameter of my function, so whenever a person searches on the name "JoNes", the parameter gets "translated" to "Jones". (this is just to play with Javascript, not mandatory)
According to this website, there is a case called Sentence Case (he also calls it Title Case), however, whenever I use .toSentenceCase, it returns a syntax error on Codecademy. I would like to know if the following code would normally work and that it's Codecademy that doesn't support it in this assignment (in other words: it doesn't expect it, so anything different than the expected is wrong) OR if it's not possible to add a case to the parameter of a function like this.
Bonus: If it's the latter, how would you fix the input coming in through search();, so it always corresponds to the demand of the first letter being upper-case, while the rest is lower case?
The function:
var search = function(lastName.toSentenceCase) {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
if (lastName === contacts[i].lastName) {
printPerson(contacts[i]);
}
}
}
search("JoNes");
Here you go:
String.prototype.toSentenceCase= function() {
return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase()
}
Then:
"JoNes".toSentenceCase();
becomes: Jones
I would try this:
String.prototype.toSentenceCase = function () {
var stringArray = this.split(" ");
for (var index = 0; index < stringArray.length; index++) {
stringArray[index] = stringArray[index].substr(0,1).toUpperCase() + stringArray[index].substr(1).toLowerCase();
}
return stringArray.join(" ");
}
//test:
var testString = new String("JoNe Is A NaMe");
console.log(testString.toSentenceCase());

Javascript function not working with an array

i have this function which loops through an array of check boxes checking if the boxes value is equal to something in a text box, i dont know whats wrong.
function checkValue(contain) {
var boxes = document.getElementsByTagName("input");
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].name == "vote[]") {
if (boxes[i].value.indexOf(contain.value) != -1) {
boxes[i].checked = true;
}
}
}
}
and this is how i call it
OnClick="uncheckAll(); checkValue(document.getElementsByName("countrylist"));"
this code is in side a echo in php which is like this echo ' ';
You cannot nest the same type of quotes in HTML.
OnClick="uncheckAll(); checkValue(document.getElementsByName(\'countrylist\'));"
Simply escape the single quotes as shown as PHP provides an easy escape mechanism.
the contain argument you're passing is an array not a string. that could be the problem?
I think your javascript might be having an issue with the name of your field being vote[].
Does it ever pass the condition:
if (boxes[i].name == "vote[]") {
1) Update the inlince call to use single quotes:
checkValue(document.getElementsByName('countrylist'))
2) Use document.getElementsByName to make the function little better:
function checkValue(contain)
{
var boxes = document.getElementsByName("vote[]");
for (var i = 0; i < boxes.length; i++)
{
boxes[i].checked = (boxes[i].value == contain.value);
}
}

Categories

Resources