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?