EnglishAdam
EnglishAdam

Reputation: 1390

Delete part of string by index position

How can I delete a part of a string by using only the index (no regex in case the character at index exists elsewhere)?

I use this, but it seems extremely convulted!!

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;

Upvotes: 0

Views: 304

Answers (5)

Abdul Jabbar
Abdul Jabbar

Reputation: 2573

To remove one specific index from your string:

str.substr(0, indexToDelete) + str.substr(indexToDelete+1, str.length);

to remove a range of indexes from your string:

str.substr(0, startIndexToDelete) + str.substr(endIndexToDelete+1, str.length);

Upvotes: 1

Gr&#233;gory Vorbe
Gr&#233;gory Vorbe

Reputation: 374

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

Result :

sringIwant to delete from

fiddle

Upvotes: 0

georg
georg

Reputation: 214959

substring is smart enough to handle invalid indexes on its own:

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 + ","

Upvotes: 1

Snickbrack
Snickbrack

Reputation: 956

then create a substring and use replace('your substring', '') it will replace the part of your string with a empty space

Upvotes: -2

evilpenguin
evilpenguin

Reputation: 5478

In your case, it's easier to use slice():

finalString = str.slice(0,index2delete)+str.slice(index2delete+1)

If you want to remove more characters, you can have 2 indexes:

finalString = str.slice(0,start_index)+str.slice(endindex+1)

http://www.w3schools.com/jsref/jsref_slice_string.asp

Upvotes: 1

Related Questions