Reputation: 50
I wish to use splice on string e.g.
console.log(removeFromString('Elie', 2, 2)) // 'El'
Upvotes: 1
Views: 6245
Reputation: 347
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);
Upvotes: 1
Reputation: 3427
Although this is not a great way but this is just to give you idea how things works in javascript.
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)
You can use split
method to convert a string into array of characters.
You can use splice
method on array of characters.
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
Upvotes: 2
Reputation: 97152
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));
Upvotes: 3
Reputation: 40
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));
Upvotes: 0
Reputation: 390
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));
Upvotes: 1