Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i remove chars between indexes in a javascript string

Tags:

javascript

i have the following:

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

how can i remove all the chars from S that reside between bindex and eindex?
therefore S will be "hi are you"

like image 577
scatman Avatar asked Mar 07 '11 08:03

scatman


People also ask

How do I remove a specific part of a string in JavaScript?

To remove all occurrences of a substring from a string, call the replaceAll() method on the string, passing it the substring as the first parameter and an empty string as the second. The replaceAll method will return a new string, where all occurrences of the substring are removed.

How do you get rid of a char in a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


2 Answers

Take the text before bindex and concatenate with text after eindex, like:

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

S is now "hi are you"

like image 161
Rasmus Striib Avatar answered Oct 04 '22 01:10

Rasmus Striib


First find the substring of the string to replace, then replace the first occurrence of that string with the empty string.

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

Another way is to convert the string to an array, splice out the unwanted part and convert to string again.

var result = S.split('');
result.splice(bindex, eindex - bindex);
S = result.join('');
like image 26
Anurag Avatar answered Oct 04 '22 00:10

Anurag