Home > Software design >  How to use splice on string in JavaScript
How to use splice on string in JavaScript

Time:10-01

I wish to use splice on string e.g.

console.log(removeFromString('Elie', 2, 2)) // 'El'

CodePudding user response:

If you really want to use splice(), you can spread the string to an array, invoke splice() on the array, and join() the results back together:

const removeFromString = (s, x, y) => {
  const array = [...s];
  array.splice(x, y);
  return array.join('');
}

console.log(removeFromString('Elie', 2, 2));

CodePudding user response:

I think this is what you want to do.

function removeFromString(string, start, count) {
    let str = string.split('');
    str.splice(start, count);
    return str.join('');
}

console.log(removeFromString('Elie', 2, 2));

CodePudding user response:

Try this:

function removeFromString(str, start, end) {
  let arr = Array.from(str);
  arr.splice(start, end);
  return arr.join(String());
}

and then use:

removeFromString('Elie', 2, 2);

CodePudding user response:

Try using following code you can get more info about slice here

let str = "Elie";
// pass start and end position to slice method ,it will not include end character like i is at 2nd position
console.log(str.slice(0, 2));

CodePudding user response:

Although this is not a great way but this is just to give you idea how things works in javascript.

  1. You can't use splice on a string because it works for arrays as it doesn’t work on strings because strings are immutable (edit after
    Sebastian Simon's comment)

  2. You can use split method to convert a string into array of characters.

  3. You can use splice method on array of characters.

  4. You can use join method to convert array of characters to make a string

let stringTitle = "Elie";   // string
let stringArray = stringTitle.split("");   // spliting string into array of characters
console.log(stringArray);
let subString = stringArray.splice(0,2).join("")  // using splice on array of characters and then join them to make a string
console.log(subString)  // output El

I would suggest using str.substring(0, 2); for this use case is a better option.

let stringExample = "Elie";
let substring = stringExample.substring(0, 2);
console.log(substring) // output El

CodePudding user response:

//The splice() method removing or replacing existing elements--

const month = ['Jan', 'March', 'April', 'June'];
month.splice(1, 0, 'Feb'); // inserts at index 1
console.log(months);

//output: Array ["Jan", "Feb", "March", "April", "June"]

  • Related