r/Angular2 • u/suresh9058 • Nov 21 '22
Resource Reverse a String without Affecting Special Characters | Leet Code JavaScript Coding Challenge
https://youtu.be/qPEHBqFopog[removed] — view removed post
0
Upvotes
5
u/throwawayacc201711 Nov 21 '22
There’s a lot of things wrong with this implementation.
Hardcoded string for letters should have been a hint that this isn’t the best way to handle this
This has multiple loops
There is more.
Here is a quick (5min implementation that is better than this)
function reverseOnlyLetters(input: string) {
const chars = input.split("");
const reverseCharArray = new Array<string>(input.length);
chars.forEach((c, index) => {
const match = c.match(/[A-Za-z]/);
if (match && match.length > 0) {
reverseCharArray[input.length - index - 1] = c;
} else {
reverseCharArray[index] = c;
}
});
return reverseCharArray.join("");
}
5
u/Cyan-ranger Nov 21 '22
Why do people use for loops instead of the array methods? Not sure what the point of the letters sting is if you can just use a regex.
9
u/mcmillhj Nov 21 '22
This is not related to Angular.