我有以下内容:
var S="hi how are you";
var bindex = 2;
var eindex = 6;
如何从S中删除位于bindex和eindex之间的所有字符?
因此,S将变为“hi are you”
我有以下内容:
var S="hi how are you";
var bindex = 2;
var eindex = 6;
如何从S中删除位于bindex和eindex之间的所有字符?
因此,S将变为“hi are you”
取出 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"
首先找到需要替换的字符串子串,然后将该字符串的第一个出现位置替换为空字符串。
S = S.replace(S.substring(bindex, eindex), "");
另一种方法是将字符串转换为数组,splice
掉不需要的部分,然后再将其转换回字符串。
var result = S.split('');
result.splice(bindex, eindex - bindex);
S = result.join('');
''
进行分割) - alexandernst尝试
S = S.substring(0, bindex)+S.substring(eindex);
With String.slice
:
S = S.slice(0, bindex) + S.slice(eindex);
一种不需要创建任何中间数组或字符串的解决方案是使用 .replace
来捕获一个组中的第一个字符,匹配你想要删除的字符,并用第一个捕获的组替换:
// keep first 3 characters, remove next 4 characters
const s = "hi how are you";
console.log(
s.replace(/(.{3}).{4}/, '$1')
);
S.split(S.substring(bindex, eindex)).join(" ");
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"
你可以:
重新构建字符串
var new_s = S.slice(1, bindex) + S.slice(bindex, eindex).replace(/\s/g, '') + S.slice(eindex)
虽然 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"
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))
substring
而已。 - undefined