如何仅使用索引删除字符串的一部分(如果索引处的字符存在于别处,则不使用正则表达式)?
我使用它,但它看起来非常令人沮丧!!
var str = "stringIwant to delete from";
var stringCodeLastIndex = str.length - 1;
var index2delete = 1;
var stringStart, stringEnd, finalString;
if (index2delete == 0) {
stringStart = "";
} else {
stringStart = str.substr(0, index2delete);
}
if (index2delete < stringCodeLastIndex) {
stringEnd = str.substr(index2delete + 1);
} else {
stringEnd = "";
}
finalString = stringStart + stringEnd;
答案 0 :(得分:1)
substring
非常聪明,可以自行处理无效索引:
str = "someXXXstring";
del = 4;
len = 3
str = str.substring(0, del) + str.substring(del + len);
document.body.innerText += str + ","
str = "somestringXXX";
del = 10;
len = 20
str = str.substring(0, del) + str.substring(del + len);
document.body.innerText += str + ","
str = "somestring";
del = 0;
len = 200
str = str.substring(0, del) + str.substring(del + len);
document.body.innerText += str + ","
&#13;
答案 1 :(得分:1)
在您的情况下,使用slice()
更容易:
finalString = str.slice(0,index2delete)+str.slice(index2delete+1)
如果要删除更多字符,可以使用2个索引:
finalString = str.slice(0,start_index)+str.slice(endindex+1)
答案 2 :(得分:1)
从字符串中删除一个特定索引:
str.substr(0, indexToDelete) + str.substr(indexToDelete+1, str.length);
从字符串中删除一系列索引:
str.substr(0, startIndexToDelete) + str.substr(endIndexToDelete+1, str.length);
答案 3 :(得分:1)
var str = "stringIwant to delete from";
var index2delete = 1;
arStr = str.split(""); // Making a JS Array of each characters
arStr.splice(index2delete,1); // Using array method to remove one entry at specified index
var finalString = arStr.join(''); // Convert Array to String
结果:
sringIwant to delete from
答案 4 :(得分:-2)
然后创建一个子字符串并使用替换(&#39;您的子字符串&#39;,&#39;&#39;)它将用空格替换字符串的部分