How to replace a substring between two indices

后端 未结 6 1969
挽巷
挽巷 2020-12-08 09:23

I want to replace text between two indices in Javascript, something like:

str = \"The Hello World Code!\";
str.replaceBetween(4,9,\"Hi\");
// outputs \"The          


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 10:20

    A more robust version of VisioN's solution that detects out of range errors and throws meaningful and easy to debug RangeErrors. If you want, you can extend the String.prototype as well.

    function replaceString(str, start, end, replace) {
      if (start < 0 || start > str.length) {
        throw new RangeError(`start index ${start} is out of the range 0~${str.length}`);
      }
      if (end > str.length || end < start) {
        throw new RangeError(`end index ${end} is out of the range ${start}~${str.length}`);
      }
      return str.substring(0, start) + replace + str.substring(end);
    }
    
    // replace in the middle of the string, replacement string can be any length
    console.log(replaceString("abcdef", 2, 4, "hhhh")); // output: "abhhhhef"
    
    // insert in the front of the string, start and end index equal to 0
    console.log(replaceString("abcdef", 0, 0, "hhhh")); // output: "hhhhabcdef"
    
    // append at the end of the string, start and end index equal to the length of the string
    console.log(replaceString("abcdef", 6, 6, "hhhh")); // output: "abcdefhhhh"
    
    // error 1: start index is greater than end index
    // console.log(replaceString("abcdef", 4, 2, "hhhh")); // output: RangeError: end index 2 is out of the range 4~6
    
    // error 2: start/end index is less than 0
    // console.log(replaceString("abcdef", -2, 2, "hhhh")); // output: RangeError: start index -2 is out of the range 0~6
    
    // error 3: start/end index is greater than length of the string
    // console.log(replaceString("abcdef", 3, 20, "hhhh")); // output: RangeError: end index 20 is out of the range 3~6

提交回复
热议问题