0

let test = 'This is the test string';

console.log(test.substr(3));

console.log(test.slice(3));

console.log(test.substring(3));

Theese methods are removing first 3 character. But i want to remove only third character from the string.

The log has to be: ' Ths is the test string'

İf you help me i will be glad. All examples are giving from the substr, slice eg. eg. Are there any different methods?

Hakan Gundogan
  • 227
  • 3
  • 14

3 Answers3

4

First, get the first 3 chars, then add chars 4-end, connect those to get the desired result:

let test = 'This is the test string';

let res = test.substr(0, 2) + test.substr(3);

console.log(res);

Since substr uses the following parameters

substr(start, length)

Start The index of the first character to include in the returned substring.

Length Optional. The number of characters to extract.
If length is omitted, substr() extracts characters to the end of the string.

We can use test.substr(3) to get from the 3'th to the last char without specifying the length of the string

0stone0
  • 34,288
  • 4
  • 39
  • 64
1

const test = 'This is the test string';
const result = test.slice(0, 2) + test.slice(3);
console.log(result);

You can achieve this by concatenating the two parts of the string, using .slice().

Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26
  • `test.length` can be removed since `slice` has `str.length` as default end param. – 0stone0 Jun 14 '21 at 12:20
  • No need to add 2nd parameter in your 2nd `.slice` call. By default it will slice till the end of string when no 2nd argument is provided :) – AdityaParab Jun 14 '21 at 12:20
0

You can achieve it using substring method and concatenating the strings

 str = "Delete me ";
 function del_one_char(string , removeAt){
      return string.substring(0, removeAt) + string.substring( removeAt + 1, string.length); 
 }
  console.log(del_one_char(str , 2))
  // result one character at 2nd position is deleted
Sanmeet
  • 1,191
  • 1
  • 7
  • 15