How to Reverse a string with numbers, but don't reverse 1 and 0?
You can replace 10
with a specified character which does not exist in the text, and after running the implemented algorithm replace it back with 10
.
let out_of_alphabet_character = '#';
var reg_for_the_alphabet = new RegExp(out_of_alphabet_character, "g");
function specific_revert(str) {
str = str.replace(/(10)/g, out_of_alphabet_character);
let temp = [];
temp = str.split('');
const backwards = [];
const totalItems = str.length - 1;
for (let i = totalItems; i >= 0; i--) {
backwards.push(temp[i]);
}
return backwards.join('').toString().replace(reg_for_the_alphabet, '10');
}
console.log(specific_revert("10 2 3 U S A"));
console.log(specific_revert("234567891010"));
You can reduce
over the matched array from using a regular expression. It's more costly than a for/loop that concatenates strings, but it was fun figuring it out.
function split(str) {
const re = /([A-Z23456789 ]+)|(10)/g
return str.match(re).reduce((acc, c) => {
// if the match is 10 prepend it to the accumulator
// otherwise reverse the match and then prepend it
acc.unshift(c === '10' ? c : [...c].reverse().join(''));
return acc;
}, []).join('');
}
console.log(split('2345678910'));
console.log(split('10 2 3 U S A'));
console.log(split('2 3 U S A10'));
Just check for the special case & code the normal logic or reversing as usual
const reverse = str => {
let rev = "";
for (let i = 0; i < str.length; i++) {
if (str[i] === '1' && i + 1 < str.length && str[i+1] === '0') {
rev = '10' + rev;
i++;
} else rev = str[i] + rev;
}
return rev;
}
console.log(reverse("10 2 3 U S A")); // returns A S U 3 2 10
console.log(reverse("2345678910")); // returns 1098765432