简体   繁体   English

JavaScript:编写一个 function 编辑一个范围内的字符串

[英]JavaScript: write a function that edits a string within a range

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.我想写出一个 function 来编辑某个范围内的字符串,如果提供的话,可能会为该范围交换另一段字符串。 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.范围是这样工作的——开始索引是包含的,结束索引是排除的(如slice ),如果范围大于字符串的长度,那么它会选择到最后。 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?它工作正常,但我想知道是否有更有效或更优雅的方式来做到这一点?

you can just use string.replace你可以只使用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.我喜欢上面的string.replace解决方案。

Another approach will be to use string.slice based on start/end provided index and optional text:另一种方法是使用基于开始/结束提供的索引和可选文本的string.slice

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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