简体   繁体   中英

javascript reverse a substring inside a string optimally

I have a scenario where in 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?

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));

This solution builds a regex with two capture groups, one for number of characters to skip (eg 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM