I have a scenario where I need to reverse a substring inside a string. The Javascript string is immutable and the traditional swapping technique on a string is not working here. So I have decided to use the string.split('') and string.join('') methods to get the solution. Please check the code below.
function reverseAString(str, startIndex, endIndex) {
let left = startIndex;
let right = endIndex;
let output = str;
while(left < right) {
const arr = output.split('');
let temp = arr[left]
arr[left] = arr[right]
arr[right] = temp;
output = arr.join('');
left += 1;
right -= 1;
}
return output
}
This is working as expected. But is there any better way to reverse the substring as the above solution is not the best way to achive reversal?