Javascript中的高效字符串操作

jos*_*ler 6 javascript string loops

我有一个字符串(HTML内容)和一个位置(索引)对象数组.字符串长度约为160万个字符,大约有700个位置对象.

即:

var content = "<html><body><div class="c1">this is some text</div>...."
var positions = [{start: 20, end: 25}, {start: 35, end: 37}....]
Run Code Online (Sandbox Code Playgroud)

我必须在字符串中的每个起始位置插入一个开口span标记,并在字符串中的每个结束位置插入一个close span标记.

最有效的方法是什么?

到目前为止,我已经尝试反向排序位置数组,然后循环,然后使用replace/splice插入标记,例如:

content = content.slice(0, endPosition) + "</span>" + content.substring(endPosition);
content = content.slice(0, startPosition) + "<span>" + content.slice(startPosition);
Run Code Online (Sandbox Code Playgroud)

(注意我是如何从最后开始循环的,以避免弄乱开始/结束位置).

但这需要大约3秒钟,这对我来说似乎缓慢且效率低下.

有什么更有效的方法呢?

geo*_*org 4

不要每次都修改大字符串,而是尝试在新缓冲区中累积已处理的“块”:

content = '0123456789'
positions = [
  [1, 3],
  [5, 7]
]

buf = []
lastPos = 0

for (let [s, e] of positions) {
  buf.push(
    content.slice(lastPos, s),
    '<SPAN>',
    content.slice(s, e),
    '</SPAN>'
  )
  lastPos = e
}

buf.push(content.slice(lastPos))


res = buf.join('')
console.log(res)
Run Code Online (Sandbox Code Playgroud)