This challenge's description is to take a string and replace the letters with the letters position in the alphabet starting from 1-index. Requires you to skip all non-characters including whitespace.
function alphabetPosition(text) {
var result = [];
var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z"]
text = text.replace(/\W*\d+/g, '').toLowerCase().split('');
for (var i = 0; i < text.length; i++)
result.push(alphabet.indexOf(text[i]) + 1);
return result.join(' ');
}
My problem is when it comes to random tests, the input will contain digits and non word characters but the Regex isn't recognizing it. The input is n8_ovuu&
and the output/error is Expected: '14 15 22 21 21', instead got: '14 0 15 22 21 21 0'
The problem lies in the Regex, but I can't figure it out. If you have any idea I would appreciate the help!
[A-Za-z] will match all the alphabets (both lowercase and uppercase).
The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string.
Add a condition in your loop:
Replace:
for (var i = 0; i < text.length; i++)
result.push(alphabet.indexOf(text[i]) + 1);
with:
for (var i = 0; i < text.length; i++) {
var j = alphabet.indexOf(text[i]) + 1;
if (j) result.push(j);
}
Note that you can define the alphabet as a string instead of an array, without any change to the above loop:
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
Here is an ES6 code solution which chains method upon method to return the result in one return
statement:
function alphabetPosition(text) {
return text.toLowerCase().split('')
.filter( c => c >= 'a' & c <= 'z' )
.map( c => c.charCodeAt(0) - 'a'.charCodeAt(0) + 1)
.join(' ');
}
console.log(alphabetPosition('n8_ovuu&'));
function alphabetPosition(text) {
return text.toLowerCase().replace(/[^a-z]/g, '')
.replace(/./g, ([c]) => ' ' + (c.charCodeAt(0) - 'a'.charCodeAt(0) + 1))
.substr(1);
}
console.log(alphabetPosition('n8_ovuu&'));
You're getting zeros because some of the characters (like _
and &
) don't match the alphabet. When .indexOf()
can't find a match, it returns -1
. You then gets + 1
added to it, making it zero.
You can either add those characters to the alphabet or you might want to ignore those by simply adding an if
clause.
for (var i = 0; i < text.length; i++) {
var index = alphabet.indexOf(text[i]);
if (index > -1) {
result.push(index + 1);
}
}
To tell your regular expression to filter non-alphabet characters, replace \W
with an explicit inverted character range [^a-zA-Z]
.
console.log("abc_def".replace(/[^a-zA-Z]/, ''));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With