Given a string, return the string without numbers. For example: for the string, "I W4nt 2 Br3ak Fr33", it should return the string "I Wnt Brak Fr"
I am extremely new to this and have been in a coding boot camp with almost zero instruction to these more "complicated" functions.
I tried the following and in reverse I’ll get a string of just numbers but with non-equality I return the original string still..
function removeNumbers(str) {
let arr = [];
for (let i = 0; i < str.length; i++) {
if (
str[i] != '0' ||
str[i] != '1' ||
str[i] != '2' ||
str[i] != '3' ||
str[i] != '4' ||
str[i] != '5' ||
str[i] != '6' ||
str[i] != '7' ||
str[i] != '8' ||
str[i] != '9'
) {
arr.push(str[i]);
}
}
return arr.join("");
}
4
Answers
This is a logic error on your side, you would want to use
AND
operator (&&
) instead ofOR
operator (||
) in your case:Else, all characters will pass the validation.
Let’s go through what happened during each loop for all the characters:
str[i]
is4
(when you reachI W4
inI W4nt 2 Br3ak
)4
matches the first checkstr[i] != '0'
and since this is usingOR
operator, it requires only 1 of the statements to be true to consideredtrue
, and as such it is pushed into the array.This is same for other numbers so all numbers are considered as valid, and is output in your final string.
As a revision,
a || b
means that only either one of them needs to be true, in order to result intrue
.a && b
means that botha
andb
has to be true, in order the result to betrue
.Truth table below for reference:
a
b
a || b
a && b
Using regular expression:
Playground: https://regex101.com/r/l2NJtN/1
Or in short:
Just use the string
replace()
method, no need for arrays.Everything between the slashes
/
is a regular expression. Here the pattern[0-9]
matches all numbers, and theg
makes it global so it matches all occurrences within the string. Then the empty string in the second argument''
replaces each number with nothing.Same as this question: How to remove numbers from a string?
Most answers are too much complicated. Don’t worry, there’s other forms to solve this problem, without RegEx or long conditionals.
First, create a list of numbers to be compared:
Then, create the
removeNumbers
function, iterating over all the characters of thestring
parameter.Inside this for loop, let’s check if the character of the iteration is not a number with the function
includes
:Then, inside in this if, concatenate the current letter on the
cleaned_string
variable.Finally, return the
cleaned_string
value:Complete code: