I wish to use splice on string e.g.
console.log(removeFromString('Elie', 2, 2)) // 'El'
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));
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
Array.prototype.splice.call("abc", 1, 0), but you’ll get an error whose cause is the string’s immutability. Also, the split–splice–join approach has already been suggested, and my comment on the other answer still holds: .split is not Unicode-aware. Please use Array.from instead.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));
.split('') is not Unicode-aware. Please use Array.from to support a larger variety of characters.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);
String() really isn’t best practice. Use "" instead.String(). That’s what you want in .join.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));
String.prototype.splicewon’t exist, because strings are immutable. Usesliceorsubstringinstead.splicecan be used with arrays, why not make a character array, then splice, then convert back to a string? Again, start with the documentation, e.g. theArraymethods. Try something on your own. All the tools you’ll need are documented there.splicedo to the string? Can you at least try to describe the algorithm? Perhaps in terms of the method names provided in the documentation links? Perhaps even in the form of code that you tried?