Bean Counting WITHOUT using for loop and regex [duplicate] - javascript

This question already has answers here:
How to count string occurrence in string?
(40 answers)
Closed 2 years ago.
I tried to solve the following problem without using the for loop:
"Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters there are in the string.
console.log(countBs("BBC")); // → 2
Thank you for your help.
Here is the code I wrote so far which doesn't work:
function countBs(word) {
let count = 0
if (word.length == 0) {
return count;
} else {
if (word[word.length - 1] == 'B') {
count++
}
return countBs(word.slice(0, word.length - 1))
}
}
console.log(countBs("BBC"))

You can easily use regex for this case:
function countBs(word) {
const matches = word.match(/B/g);
return matches && matches.length || 0;
}
Basically it globally searches for occurrences of 'B'. If it find it, it returns the length of it, if the matches are null it will return 0.
Simpler less expressive:
function countBs(word) {
return (word.match(/B/g) || []).length;
}

Related

Explain work of lastIndexOf in this for loop [duplicate]

This question already has answers here:
confusion about lastIndexOf in javascript
(3 answers)
Closed 8 months ago.
Can somebody explain to me how exactly lastIndexOf works here?
To be specific: I do not understand how comparing str[i] !== i works here. How does it detect if the character is repeating?
This had to be a simple exercise to find if str has unique characters that are not going twice in the same str.
isUnique('abcdef'),
isUnique('89%df#$^a&'),
isUnique('abcaef'));
function isUnique(str)
{
for(var i = 0; i < str.length; i++)
{
if(str.lastIndexOf(str[i]) !== i) return false;
}
return true;
}
assume you have a string like this: 'abcaef', let's start and check that if it is unique or not...
we start from first char: 0 and str[0] is a and if all chars in str are unique, we expect that lastIndexOf("a") return 0 but it return 3 and it means there is another a that it is not in position 0
note that lastIndexOf return index from left, but it check from right and return index of first occurrence from right:
a b c a e f
0 1 2 3 4 5 <-

Why is my function returning "newLine.unshift(startN) is not a function" [duplicate]

This question already has answers here:
Parameters as storage in recursion - Return an array using recursion of all values from startNum to endNum
(4 answers)
Closed 1 year ago.
I have been trying to write a recursive function to get a range of numbers, but I am getting an error saying 'newLine. unshift(startN) is not a function'.
Following is the code:
function rangeOfNumbers(startN, endN) {
if (startN - endN === 0) {
return "The starting number will always be less than or equal to the ending number";
} else {
const newLine = rangeOfNumbers(startN + 1, endN);
newLine.unshift(startN);
return newLine;
}
}
console.log(rangeOfNumbers(1, 7));
Can someone please help me to find the reason for getting the error mentioned?
rangeOfNumbers(1, 7) / newLine = rangeOfNumbers(2, 7)
rangeOfNumbers(2, 7) / newLine = rangeOfNumbers(3, 7)
...
rangeOfNumbers(7, 7) / newLine = "The starting number will always be ..."
typeof newLine = String
newLine.unshift() >> undefined // unshift isn't available JS Strings

String of numbers can't start with zero. Other Solutions? [duplicate]

This question already has answers here:
Remove leading zeros from a number in Javascript [duplicate]
(3 answers)
Closed 5 years ago.
I have a string that only contains numbers, but the string can not start with a zero.
The first thing I cam up with was this:
let myNumber = "0052";
myNumber = myNumber.split('');
for (let i = 0; i < myNumber.length; i++) {
if (myNumber[i] == '0') {
myNumber.splice(i, 1);
i--;
} else {
break;
}
}
console.log(myNumber);
console.log('result:', myNumber.join(''));
Everything works fine like that.
I thought there might be an other way without using a classical for-loop.
My attempt with a for-of loop failed. As soon as I remove the first entry of my array, the index of the loop does not reset, so it skips the second zero in my array. Here is the code for that:
let myNumber = "0052";
myNumber = myNumber.split('');
for (let n of myNumber) {
if (n == '0') {
myNumber.shift();
} else {
break;
}
}
console.log(myNumber);
console.log('result:', myNumber.join(''));
What other solutions to this problem are there? Is there a more performant solution?
What you're probably looking for is parseInt function.
const result = parseInt("0052", 10).toString();
console.log(result);
I also added toString() to convert number to a string. parseInt also accepts second argument - the radix. Read more about parseInt
Regexp: /^[0]+/
let myNumber = "0000000520";
console.log(myNumber.replace(/^[0]+/, ''))
Use
parseInt('0052') = 52
or
parseFloat('0052.29') = 52.29 if your number is float type:
I just have different and simpler approach than yours :)
while(myNumber.length){
if(myNumber.charAt(0) == '0')
myNumber = myNumber.substring(1, myNumber.length);
}
DEMO : https://jsbin.com/falejuruwu/1/edit?js,console

How to remove all non-alphabet characters, javascript [duplicate]

This question already has answers here:
Java, Check if a String is a palindrome. Case insensitive
(5 answers)
Closed 5 years ago.
I am asked to check if a string is a Palindrome.
To not be case sensitive. To ignore all characters that are not letters.
My Answer
function palindrome(str) {
var oldStr = str.toLowerCase().replace(/\s+|\,|\.|\_|\-|\:|\(|\)|\/|\\/g, '');
var newStr = str.replace(/\s+|\,|\.|\_|\-|\:|\(|\)|\/|\\/g, '').split("").reverse().join("").toLowerCase();
if ( oldStr === newStr){
return true;
}
else {
return false;
}
}
palindrome("ininiNI");
The function is to be checked with any string possibility.
Example: ("0_0 (: /-\ :) 0-0") Which according to the requirements should return true.
I could not find a better solution in JavaScript then the one above.
Is there a faster/better way than just writing out each possible character to be removed/replaced? (especially since what I wrote is far from exhaustive...)
There is no need to call toLowerCase() and replace() twice. You can also cut string in a half, reverse one part and then compare. That way you can speed up your function few times at least.
Optimized function may look like that:
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-z]/g, '');
var max = str.length - 1;
for (var i = Math.floor(max / 2); i >= 0; i--) {
if (str[i] != str[max - i]) {
return false;
}
}
return true;
}
palindrome("inabcbani"); //true
palindrome("abcddcba"); //true
palindrome("a*#$(b)&^#%#%(*a"); //true
palindrome("abba"); //true
palindrome("abcdba"); //false
For loop will be the fastest way in my opinion as it's quick and simple. You can return false once you find first character that doesn't match.

jQuery has/ contains words [duplicate]

This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 9 years ago.
I'd like to achieve that, if "clientpsseabq" string is contained in variable Var_words then equal true, else false. I just have no idea what method or function do I need to use?
var Var_words = "https://www.go.me/outputsearchs/clientpsseabq"
if ( Var_words contains string "`clientpsseabq`"){
return true;
}else{
return false;
}
if someone could help me how can I complete this task?
Use the (native JavaScript) function String.indexOf():
if(Var_words.indexOf('clientpsseabq') !== -1) {
return true;
} else {
return false;
}
.indexOf() returns the index of the string. If the string is not found, it returns -1.
A smaller, cleaner solution would be to simply return the value of the conditional directly:
return (Var_words.indexOf('clientpsseabq') !== -1);
You can try this
if (Var_words.indexOf("clientpsseabq") >= 0)
or with care of case sensitivity
if (Var_words.toLowerCase().indexOf("clientpsseabq") >= 0)
{
// your code
}
use a regular expression to test for the case
if(/clientpsseabq/.test(Var_words)){
//given string exists
} else {
//given string does not exists
}
if(Var_words.indexOf("clientpsseabq") >= 0))
{
}

Categories

Resources