首页 > 解决方案 > 如何通过在指定范围内引入点来减少字符串

问题描述

我想... 在指定范围之间引入,以便我可以看到文件format

假设我有一个字符串 sinchan is going to school in india.mp4

假设我想在16 到 19...之间介绍pos/index

我的字符串将如下所示: sinchan is going...in india.mp4

我的伪代码:

function getFilename(str, startingDot, endingDot, maxLengthRequired) {
  str.(introduce `startingDot` till 'endingDot' do not exceed string length more than `maxLengthRequired`)
}

alert(insert("sinchan is going to school in india.mp4", 16, 19,31));

输出:(sinchan is going...in india.mp4可能相差一两个字符)

请帮助我提前谢谢!

标签: javascriptjqueryhtmlnode.js

解决方案


let str = 'sinchan is going to school in india.mp4'
function trans (str, start, end, max) {
    if (start + 3 > max) return new Error('start add three should not more than max')
    let result = str.slice(0, start) + '...' + str.slice(end)
    if (result.length <= max) return result
    return result.slice(0, start + 3) + result.slice((start + 3 - max))
}
trans(str, 16, 19, 31)

推荐阅读