如何在JavaScript字符串中删除索引之间的字符

31

我有以下内容:

var S="hi how are you";
var bindex = 2;
var eindex = 6;

如何从S中删除位于bindex和eindex之间的所有字符?
因此,S将变为“hi are you”

11个回答

58

取出 bindex 之前的文本,并与 eindex 之后的文本进行拼接,例如:

var S="hi how are you"; 
var bindex = 2; var eindex = 6; 
S = S.substr(0, bindex) + S.substr(eindex);

S现在是"hi are you"


3
这似乎是最安全的方式。应该接受这个答案。 - Prajeeth Emanuel
3
我喜欢这个,它避免了友军误伤。 - Niki Romagnoli
1
我也同意这个答案应该是被采纳的答案。 - Yanal-Yves Fargialla
2
substr 正在被弃用。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/substr - Cleanshooter
新的选择只是substring而已。 - undefined

19

首先找到需要替换的字符串子串,然后将该字符串的第一个出现位置替换为空字符串。

S = S.replace(S.substring(bindex, eindex), "");

另一种方法是将字符串转换为数组,splice掉不需要的部分,然后再将其转换回字符串。

var result = S.split('');
result.splice(bindex, eindex - bindex);
S = result.join('');

21
第一种方法可以替换比你想象的更多的东西。 - alexandernst
1
进一步说,如果字符串中存在Unicode字符,第二种方法将会出现奇怪的问题。(因为你使用了''进行分割) - alexandernst
1
.replace() 只会替换给定字符串的第一个出现位置。如果有什么不必要的东西,这个方法只会移除它。 - Prajeeth Emanuel

13

尝试

S = S.substring(0, bindex)+S.substring(eindex);

9

With String.slice:

S = S.slice(0, bindex) + S.slice(eindex);

如果你已经知道索引的话,这种方式看起来会更高效。 - Dominic

3

一种不需要创建任何中间数组或字符串的解决方案是使用 .replace捕获一个组中的第一个字符,匹配你想要删除的字符,并用第一个捕获的组替换:

// keep first 3 characters, remove next 4 characters
const s = "hi how are you";
console.log(
  s.replace(/(.{3}).{4}/, '$1')
);


2

S.split(S.substring(bindex, eindex)).join(" ");


1
以下函数返回切片函数的补集结果:
 String.prototype.remainderOfSlice = function(begin, end) {

    begin = begin || 0
    end = (end === undefined) ? this.length : end 

    if (this.slice(begin, end) === '') return this + ''
    return this.slice(0, begin) + this.slice(end) 
 }

示例:

例子:

 "hi how are you".slice(2, 6) // " how"
 "hi how are you".remainderOfSlice(2, 6) // "hi are you"

 "hi how are you".slice(-2, 6) // ""
 "hi how are you".remainderOfSlice(-2, 6) // "hi how are you"

1

你可以:

  1. 从 bindex 和 eindex 中获取子字符串
  2. 从该字符串中删除空格
  3. 重新构建字符串

    var new_s = S.slice(1, bindex) + S.slice(bindex, eindex).replace(/\s/g, '') + S.slice(eindex)


抱歉,我误读了您的问题,将“删除所有空格”读成了“删除所有字符”。 - Don

1

不要使用slice; 尝试使用splice

虽然 slice 很好用,但它像 substring 一样被设计成获取内容,而不是删除内容。

注意: splice 是为数组编写的。

好消息: 字符串很容易转换为数组。

String.prototype.splice = function(start, deleteCount) {
  const newStringArray = this.split('')
  newStringArray.splice(start, deleteCount)
  return newStringArray.join('')
}

'Hello World'.splice(2, 5)
// Output -> "Heorld"

这并没有真正解释为什么你不应该使用切片 - 它的设计初衷是获取字符串的部分,而以上示例中它正在执行这个操作(即使最终结果是将字符串重新组合)。split和join操作会使这个函数变得非常慢。 - Sandy Gifford

0
假设您只有起始索引bindex和要删除的字符串长度,而结束索引是不确定的。
这种情况通常用于密码学中,当您想要从解密后的字符串中删除(在加密之前已插入到已知索引处)而不暴露盐值时;您可以公开盐长度而不是盐值。

function removeSalt(str, bindex, saltlen) {
    
    let front = str.slice(0, bindex)
    return front + str.slice(front.length + saltlen)
}

var s = "how was45r7% your day?" // can be result from a decryption function
console.log (removeSalt(s, 7, 5))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接