Javascript word counter [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I wanted to make a basic word counter based on the amount of whitespaces in a sentence, but for some reason it doesn't work.
function countWords(str) {
if (typeof str == "string" && str.length > 0) {
var counter = 1;
for (var i; i < str.length; i++) {
if (str[i] === " ") {
counter += 1;
}
}
return counter;
} else {
throw Error("You must input a string.");
}
}
console.log(countWords("hello World"));
This throws 1 instead of 2.

You shouldn't use a loop for this. You would rather just split the string by space and take the resulting array's length
let countWords = str => str.split(' ').length;
console.log(countWords("foo bar"));

Initialize i to zero.
Replace for (var i; with for (var i=0;

You must initilize the counter inside the for, like var i = 0; here is your code
function countWords(str) {
if (typeof str=="string" && str.length>0) {
var counter=1;
for (var i;i<str.length;i++) {
if (str[i]===" ") {
counter+=1;
}
}
return counter;
}
else {
throw Error("You must input a string.");
}
}
countWords("hello World");
Or you can count words with str.split(" ").length

Your for loop was wrong
function countWords(str) {
if (typeof str=="string" && str.length>0) {
var counter=1;
for (var i = 0;i<str.length;i++) {
if (str[i]===" ") {
counter+=1;
}
}
return counter;
}
else {
throw Error("You must input a string.");
}
}
var str = "hello World this is me";
console.log(countWords(str));

Related

whats the problem in my code? I want to implement a JavaScript stack function and it resulted to NaN [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
//2
function Stack(){
this.dataStore=[];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
this.clear = clear;
}
function push(element){
this.dataStore[this.top++] = element;
}
function pop(){
this.dataStore[--this.top];
}
function peek(){
return this.dataStore[this.top-1];
}
function length(){
return this.top;
}
function clear(){
this.top = 0;
}
var input = "100/5";
var operands = new Stack();
var operators = new Stack();
var operandsFlip = new Stack();
var postfixStr = "";
function convertInfixToPostfix(input) {
var numStr = "";
for (var i = 0; i < input.length; i++) {
var curr = input[i];
if (curr === "+" || curr === "-" || curr === "*" || curr === "/") {
operators.push(curr);
operands.push(numStr);
numStr = "";
} else {
numStr += curr;
}
}
operands.push(numStr);
while (operands.length() > 0) {
operandsFlip.push(operands.pop());
}
var operand1 = operandsFlip.pop();
var operand2 = operandsFlip.pop();
var operator = operators.pop();
console.log("Postfix expression: " + operand1 + " " + operand2 + " " + operator);
var result = eval(operand1 + operator + operand2);
console.log("Posfix evaluated: " + result);
}
convertInfixToPostfix(input);
A postfix expression evaluator works on arithmetic expressions taking the following
form:
op1 op2 operator
Using two stacks—one for the operands and one for the operators—design and
implement a JavaScript function that converts infix expressions to postfix expres‐
sions, and then use the stacks to evaluate the expression.
and this is the output:
Postfix expression: undefined undefined undefined Posfix evaluated: NaN
Your pop() function misses the return keyword and therefore always returns undefined.
function pop(){
return this.dataStore[--this.top];
}

Create a function that takes a word and returns true if the word has two consecutive identical letters [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
// Create a function that takes a word and returns true if the word has two consecutive identical letters.
What am I doing wrong?
module.exports = (word) => {
for (let i = 0; i <= word.length; i++) {
for (let j = i + 1; j <= word.length; j++) {
if (word[j] == word[i]) {
return true;
}
} return false;
}
};
You can do this with only 1 loop.
function hasConsecutiveIdenticalLetters(word){
for (let i = 1; i < word.length; i++) {
if (word[i-1] === word[i]) {
return true;
}
}
return false;
}
You can also achieve this like below using some
const hasConsecutiveIdenticalLetters = (word: string) => (word).split('').some((letter, index) => letter === word[index + 1]);

Delete identical elements from string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Got string, need to delete same words from there.
Here is my code. I tried to split string into array and then sort but it didn't work. It didn't even go through my if. I would like to hear your advice and maybe working code :)
var str = "I wont go anywhere as soon as I wont go there";
var array = str.split(" ");
document.getElementsByTagName('p')[0].innerHTML = str;
document.getElementsByTagName('p')[1].innerHTML = array;
document.getElementsByTagName('button')[0].onclick = function () {
for (var i = 0; i < array.length; i++) {
if (array[i] == array[i + 1]) {
array.splice(i, 1);
}
}
document.getElementsByTagName('p')[2].innerHTML = array;
}
If you like one-lines try this
var reducedString = array.reduce(function(out, s) {
return out.indexOf(s) == -1 ? out + ' ' + s : out;
},'').substring(1);
or in ES6
var reducedString = array.reduce( (out, s) => out.indexOf(s) == -1 ? out + ' ' + s : out);
Your problem is that you don't check every array element with every other array element.
Your code:
for (var i = 0; i < array.length; i++) {
if (array[i] == array[i + 1]) {
array.splice(i, 1);
}
}
Just checks array elements in sequence.
Try:
for (var i = 0; i < array.length; i++) {
for(var j = 0; j < array.length; j++){
if (array[i] == array[j] && i != j) {
array.splice(i, 1);
}
}
}
You can use an ES6 Set with the spread syntax after splitting the sentance:
const str = "I wont go anywhere as soon as I wont go there";
const unique = [...new Set(str.split(' '))].join(' ');
console.log(unique);
In ES5 you can use Array#reduce with a dictionary object.
var str = "I wont go anywhere as soon as I wont go there";
var dict = Object.create(null); // creates an empty object, without inherited properties and methods
var unique = str.split(' ').reduce(function(arr, w) {
if(!dict[w]) {
arr.push(w);
dict[w] = true;
}
return arr;
}, []).join(' ');
console.log(unique);
You can just replace the substring you are searching for
var ret = "data-123".replace('data-','');
console.log(ret);

Longest Even word [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I need to find the longest even word from a sentence.
I've tried this code for finding the largest word.
But I need the even word.
Can anyone please help me?
function FindlongestWord(input) {
var arrWords = input.split(' ');
var wordlength = 0;
var word = '';
arrWords.forEach(function(wrd) {
if (wordlength < wrd.length) {
wordlength = wrd.length;
word = wrd;
}
});
return word;
}
Using modulus operator in the if statement
arrWords.forEach(function(wrd) {
if (wordlength < wrd.length && wrd.length % 2 == 0) {
wordlength = wrd.length;
word = wrd;
}
});
function FindlongestWord(input) {
var arrWords = input.split(' ');
var wordlength = 0;
var word = '';
arrWords.forEach(function(wrd) {
if (wordlength < wrd.length && !wrd.length%2) {
wordlength = wrd.length;
word = wrd;
}
});
return word;
}
Alternative solution.
const longestWord = (str) => str.split(' ').filter(v => !(v.length % 2))
.sort((a,b) => b.length - a.length)[0];
console.log(longestWord('hi there hello four longer longestt'));

Uncaught SyntaxError: missing ) after argument list in loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I keep getting the same error in my code on line 21.
if(typeof jQuery === undefined){
throw "jQuery is required for sapphire to work. Didn't you read the README?";
}
(function ( $ ) {
$.fn.slider = (function(options,images) {
var settings = $.extend({
slideCount: 4,
animationType:"none",
slideDuration:2000,
sliderSize:1100,
looptimes:300000000000000000000000000000000000000000
},options);
for(var i = 0; i<options.looptimes; i++){
var j = 0;
$("#sapphire-slide").append("<img src='"+images[j]+"'>");
setTimeout(function() {
if(j<options.slideCount-1)
j++;
}else if(j===options.slideCount-1){
j=0;
}
},options.slideDuration);
}
);
})( jQuery );
I am not sure what is causing this error, and it looks like perfectly fine syntax to me. Thanks!
you've got an extra closing brace for the if in the function that you're passing to setTimeout:
if (j < options.slideCount - 1)
j++;
// the errant closing brace is on the next line:
}
else if(j === options.slideCount - 1)
{
j = 0;
}
Or, as others have mentioned, add an opening brace to the if to make a proper block:
if (j < options.slideCount - 1)
{ // you need this opening brace
j++;
}
else if(j === options.slideCount - 1)
{
j = 0;
}
You are missing the opening { on the if and you are missing the closing } on the second last line, before the ):
(function ($) {
$.fn.slider = (function (options, images) {
var settings = $.extend({
slideCount: 4,
animationType: "none",
slideDuration: 2000,
sliderSize: 1100,
looptimes: 300000000000000000000000000000000000000000
}, options);
for (var i = 0; i < options.looptimes; i++) {
var j = 0;
$("#sapphire-slide").append("<img src='" + images[j] + "'>");
setTimeout(function () {
if (j < options.slideCount - 1) { // <--- add this {
j++;
} else if (j === options.slideCount - 1) {
j = 0;
}
}, options.slideDuration);
}
}); // <--- add a } on this line
})(jQuery);
Note that fixing this sort of thing is just a matter of counting brackets and parentheses and making sure they're balanced.

Categories