JavaScript:编写一个函数来编辑一个范围内的字符串

Joj*_*oji 2 javascript

我想写出一个函数来编辑某个范围内的字符串,如果提供的话,可能会为该范围交换另一段字符串。范围是这样工作的 - 开始索引是包含的,结束索引是不包括的(比如slice),如果范围大于字符串的长度,那么它会选择到结尾。如果起始索引超出字符串范围,则忽略整个操作。例如,

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

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

editText(string, startIdx, endIdx) // 'HLO' 
Run Code Online (Sandbox Code Playgroud)
const string = 'HELLO'
const startIdx = 2
const endIdx = 6
const textToAdd = 'y there'
editText(string, startIdx, endIdx,textToAdd)  // 'HEy there'
Run Code Online (Sandbox Code Playgroud)

这是我的尝试:

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('')
}

Run Code Online (Sandbox Code Playgroud)

它工作正常,但我想知道是否有更有效或更优雅的方法来做到这一点?

Bel*_*mir 5

你可以使用 string.replace

试试这样:

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