JavaScript: write a function that edits a string within a range

Viewed 82

I wanted to write out a function to edit a string from a certain range, and potentially swap another piece of string for that range if provided. The range works like this - the start index is inclusive and end index is exclusive (like slice) and if the range is bigger than the length of the string then it selects up to the end. if the start index is out of the range of the string then the entire operation is ignored. For example,

const string = 'HELLO'
const startIdx = 1
const endIdx = 3

editText(string, startIdx, endIdx) // should return 'HLO' 
const string = 'HELLO'
const startIdx = 1
const endIdx = 3
const textToAdd = 'y there'

editText(string, startIdx, endIdx) // 'HLO' 
const string = 'HELLO'
const startIdx = 2
const endIdx = 6
const textToAdd = 'y there'
editText(string, startIdx, endIdx,textToAdd)  // 'HEy there'

here is my attempt:

function editText(string, startIdx, endIdx, textToAdd) {
    if(startIdx < 0 || startIdx >= string.length) return string
    const strArr = string.split('')
    if(textToAdd) {
        strArr.splice(startIdx, endIdx - startIdx, textToAdd)
    } else {
        strArr.splice(startIdx, endIdx - startIdx)
    }

    return strArr.join('')
}

It works fine but I wonder if there is any more efficient or more elegant way to do that?

2 Answers

you can just use string.replace

try like this :

function editText(string, startIdx, endIdx, textToAdd=null) {
    if(startIdx < 0 || startIdx >= string.length) return string
   return string.replace(string.substring(startIdx, endIdx), textToAdd || "")
}

I like solution with string.replace from above.

Another approach will be to use string.slice based on start/end provided index and optional text:

function editText(str, start, end, extraText = '') {
    return str.slice(0, start) + extraText + str.slice(end, str.length);
}

Related