0

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?

4
  • 1
    javascript has a reverse method that will do it for you. Commented Jan 20, 2023 at 7:22
  • Hi @Layhout. Thanks for the quick response. My question is not with an array but with a substring inside a string. For example, let us take the string "hello world!". My scenario is to reverse the substring "hello". So the output should be like "olleh world!". The solution posted by me in the question works well with the scenario. But it is not an optimal one. Commented Jan 20, 2023 at 7:41
  • well, an optimal way to reverse a string is to split it up into an array, reverse it and join it back. or another little less optimal way is to declare a new string variable, create a reverse loop and call charAt method on the substring to concatenate to the new string variable. Commented Jan 20, 2023 at 7:49
  • Yes, @Layhout. In my case, I am doing the same thing but doing the string splitting multiple times. But with your solution, splitting the string only once is sufficient. Agreed. Commented Jan 20, 2023 at 8:09

2 Answers 2

2

here is your function but simplify. we can chain calling string method into array method. Array.prototype.reverse() is used to reverse an array and Array.prototype.join() is used concatenate all the element(s) in an array into a string. String.prototype.substring() is used to cut string out of the original string but does not alter/change the original string.

function reverseASubstring(str, startIndex, endIndex) {
    let reversedStr = str.substring(startIndex, endIndex).split("").reverse().join("");
    return str.substring(0, startIndex) + reversedStr + str.substring(endIndex);
}

console.log(reverseASubstring("Tony is Tony in reverse.", 0, 4));

Sign up to request clarification or add additional context in comments.

1 Comment

It is a cleaned and optimal one compared to my proposed solution. It will definitely reduce some looping. +1.
0

This solution builds a regex with two capture groups, one for number of characters to skip (e.g. start index), and one for the number of chars to reverse. With this you can apply a single regex replace that reverses the second capture group using .split('').reverse().join('')

function reverseASubstring(str, start, end) {
    let regex = new RegExp('^(.{' + start + '})(.{' + (end - start + 1) + '})');
    return str.replace(regex, (m, c1, c2) => c1 + c2.split('').reverse().join(''));
}

let str = 'Hello world.';
console.log(str, 0, 4, '=>', reverseASubstring(str, 0, 4));
console.log(str, 6, 10, '=>', reverseASubstring(str, 6, 10));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.