totalVowels variable is not updating [duplicate] - javascript

This question already has answers here:
Count number of matches of a regex in Javascript
(8 answers)
Closed 4 years ago.
My little function doesn't seem to update the totalVowels variable.
My train of thought at the moment is: the argument is converted into an array, the array is iterated through, and if the index matches against my vowel regex, my totalVowels var will add 1 per each match.
I feel like the solution is right under my nose, but I've been changing lots of little things around to get this to work and I'm currently out of ideas.
function VowelCount(str) {
let strArr = str.split('');
let totalVowels = 0;
let vowel = /a|e|i|o|u/gi
for (let i = 0; i < strArr.length; i++) {
if (strArr[i] === vowel) { totalVowels++ }
}
return totalVowels;
}
console.log(VowelCount('vowel'));

Use .match() instead of strArr[i] === vowel for your if condition check because you're using a regex:
function VowelCount(str) {
let strArr = str.split('');
let totalVowels = 0;
let vowel = /a|e|i|o|u/gi
for (let i = 0; i < strArr.length; i++) {
if (strArr[i].match(vowel)) {
totalVowels++
}
}
return totalVowels;
}
console.log(VowelCount('hello there'));

Related

I want to know that how can I print each letter of my string by using for loop in javascript [duplicate]

This question already has answers here:
How can I process each letter of text using Javascript?
(24 answers)
Closed 4 months ago.
I can't print each letter of my name
let str = "Ashman"
console.log(str[0])
for ( let i = 0 ; str<str.length; i++) {
console.log(str)
}
You are almost correct.
console.log(str[i]) should work and str<str.length should be i<str.length
let str = "Ashman";
for (let i = 0; i < str.length; i++) {
console.log(str[i])
}
To access each letter you need to insert your console.log(str[0]) inside for loop and change the [0] using your for loop variable.
let str= "Ashman";
for(let i = 0; i < str.length; i++){
let x = str[i];
console.log(x)
}

Why this code is not working as expected? I want to reverse a string but it is outputting the same string [duplicate]

This question already has answers here:
How do you reverse a string in-place in JavaScript?
(57 answers)
Closed 6 months ago.
When I write same logic in C programming it reverse the string but in Javascript it is not working, Can somebody help to figure out why? Thanks in advance.
function reverse(str) {
let res=str;
for(let i = 0; i < str.length/2; i++) {
let temp = res[i];
res[i] = res[res.length-i-1];
res[res.length-i-1] = temp;
}
return res;
}
console.log(reverse("anil"))
Strings in JavaScript are immutable.
You can read a character from a position with foo[index] but you can't write to it.
Convert the string to an array of single-character strings with split. Then convert it back to a string (with join) at the end.
function reverse(str) {
let res = str.split("");
for (let i = 0; i < str.length / 2; i++) {
let temp = res[i];
res[i] = res[res.length - i - 1];
res[res.length - i - 1] = temp;
}
return res.join("");
}
console.log(reverse("anil"))
That said. Arrays have a reverse method, so you don't need to reinvent the wheel.
function reverse(str) {
let res = str.split("");
res.reverse();
return res.join("");
}
console.log(reverse("anil"))

creating a for-loop that prints # signs instead of number values [duplicate]

This question already has answers here:
How to print a half pyramid in javascript
(9 answers)
How to print star pattern in JavaScript in a very simple manner? [closed]
(22 answers)
Closed 1 year ago.
im trying to write a code that outputs lines of '#' signs that increase by one for each value until the input number is reached.
for example, when triangles(3) is called my desired output is:
'#'
'##'
'###'
ive learned how to create this sequence with number values instead of the '#' signs but not sure how to achieve this output displayed above. thanks!
function triangles(num) {
let number = '';
for (let i = 1; i <= num; i++) {
console.log(number += i);
}
}
triangles(5)
this outputs:
'1'
'12'
'123'
'1234'
'12345'
You can use String.prototype.repeat() to repeat the pound (#) character as specified by the current value of i, without needing to declare a new variable to store it:
function triangles(num) {
for (let i = 1; i <= num; i++) {
console.log('#'.repeat(i));
}
}
triangles(5);
function triangles(num) {
let symbol = "#";
for (let i = 1; i <= num; i++) {
console.log(Array(i).fill(symbol).join(""));
}
}
triangles(5);
function triangles(num) {
const c = "#";
for (let i = 1; i <= num; i++) {
console.log(c.repeat(i));
}
}
triangles(5)
You don't have to use console.log to print number += i specifically. If you want to print '#' multiple times, you can use #Terry's answer (which is shorter) or you can use another for loop in your code (this approach could be simpler for beginners).
function triangles(num) {
let number = '';
for (let i = 1; i <= num; i++) {
number++;
let poundkeys = '';
// dont use i again, name it something else (like j or k)
for (let j = 1; j <= number; j++) {
// just like you do number += i, add a pound symbol to poundkeys
poundkeys += '#';
}
// now, log poundkeys
console.log(poundkeys);
}
}
triangles(5);
Also, a quick tip. Generally, it is better not to log number += i. Instead of:
console.log(number += i);
It is encouraged and more readable if you separate them:
number += i;
console.log(number);

How to Count the Frequencies of a Word in a String [duplicate]

This question already has answers here:
Counting occurrences of a word in a string Javascript [closed]
(2 answers)
Count the occurrence of each word in a phrase using javascript
(2 answers)
Closed 3 years ago.
I need to write a function that counts the frequencies of each word in the string in the given parameter of a function. I was wondering, what is the best way to do this?
For example, if the string in the parameter was "Mark cow mark cow the"
The count for each word would be:
Mark: 1
mark: 1
cow: 2
the: 1
My function:
function calcFrequencies(s){
var a = [], b = [], prev;
var words = s.split(" ");
for ( var i = 0; i < words.length; i++ ) {
}
}
Just to clarify, I am okay with whatever solution you come up with, I just figured it probably could involve splitting and looping through arrays, I just can't seem to figure it out.
You can create a Map to keep track of the count of each word.
function calcFrequencies(s) {
let count = new Map();
var words = s.split(" ");
words.forEach(word => {
let c = count.get(word) || 0;
c++;
count.set(word, c);
});
return count;
}
let result = calcFrequencies("Mark cow mark cow the");
for (let [key, value] of result.entries()) {
console.log(key + ": " + value);
}

Regex for same word shows first false and then true [duplicate]

This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 6 years ago.
I have problem with testing string with regex.
After iterations "aab", "aab", "aba".. here comes the problem when testing string "baa" first time is ok, result is false because regex test is setup to check is there repeating letter inside string, but when testing again "baa" result is now true. Why is this happening?
Here is the code:
//Here are function for swaping letters
String.prototype.swapLetters=function(index) {
var temp = this.split("");
var n = temp[index];
temp[index]=temp[index+1]; temp[index+1]=n;
var str1 = temp.join("");
return str1;
}
function permAlone(str) {
//the function for calculating number of total combinations
function returnFactorial(num){
if(num===0){
return 1;
} else {
return returnFactorial(num-1)*num;
}
}
var combs = returnFactorial(str.length);
var c = 0;
var permutations = 0;
var reg = new RegExp(/(.)\1+/g);
for (var i = 0; i < combs; i++) {
if(c>=str.length-1){
c = 0;
}
str = str.swapLetters(c);
if(!reg.test(str)){
permutations++;
console.log(str);
}
c++;
}
}
permAlone('aab');
Firstly, the condition you have if(!reg.test(str)){} should not have a !(not) in it if you intend to identify a regex match. I am not sure if that is what you wanted, though.
Secondly, I removed the 'global' match flag 'g' so that the regex is basically "reset" to start matching from the beginning of the text before each execution. This is because a single RegExp object when executed multiple times, starts to match the text each time from the last match index. This can give you a detailed explanation for this. Why RegExp with global flag in Javascript give wrong results?.
Try this.
//Here are function for swaping letters
String.prototype.swapLetters=function(index) {
var temp = this.split("");
var n = temp[index];
temp[index]=temp[index+1]; temp[index+1]=n;
var str1 = temp.join("");
return str1;
}
function permAlone(str) {
//the function for calculating number of total combinations
function returnFactorial(num){
if(num===0){
return 1;
} else {
return returnFactorial(num-1)*num;
}
}
var combs = returnFactorial(str.length);
var c = 0;
var permutations = 0;
var reg = new RegExp(/(\w)\1+/);
for (var i = 0; i < combs; i++) {
if(c>=str.length-1){
c = 0;
}
str = str.swapLetters(c);
console.log("case : " + str);
if(reg.test(str)){
permutations++;
console.log(str + " has repeated letters");
}
c++;
}
}
permAlone('aab');

Categories

Resources