CodeNewbie Community 🌱

Cover image for How to master working with strings in JS!
Kai Wenzel
Kai Wenzel

Posted on

How to master working with strings in JS!

When you are coding on a project, you definitely come to strings. Espacially as a beginner most don't know how to effectively work with them and how you can get the result you want. To get you there I'm going to introduce you to Splice(), Slice() and Split() in this article.

Splice, Slice, Split … they all start with S … Splice and Slice are almost twin … for me, sometimes it’s hard to memorize them, and it’s confusing to use them at the right place.

Before detailing each of them, let’s have a pizza 🍕 !

First, let’s say we have a sliced pizza, and we number each piece of them with 1, 2 … to 10, and we have a machine called splice. The splice machine can help us add or remove a piece of pizza. For example, with splice(1, 1), we remove one piece of pizza starting from first piece ( so the second piece is removed ). Beside the splice machine, we have another machine called slice. The slice machine helps us to extract some pieces of pizza. It first creates a new pizza which is the same as the original one, and take some pieces of pizza out from the new one. For example, with slice(2, 3), we extract one piece of pizza starting from second piece to third piece, but excluding the third one. Finally, we have another machine called split, the split machine helps us to split the pizza by “something”, for example, we want to split the pizza by sausage.

Pizza demonstration of splice, slice and split.

Splice

splice() is a method of Array object. It’s a destructive function since it changes the content of the input array.

Array.prototype.splice()
Enter fullscreen mode Exit fullscreen mode

The splice() method changes the contents of an array by removing **existing elements or **adding new elements

array.splice(start, [deleteCount], [item1], [item2])
Enter fullscreen mode Exit fullscreen mode
var example = ['A', 'B', 'C', 'D'];

example.splice(2, 0, 'E');       // remove 0 item, and insert 'E' at 2-index 

console.log(example);
// ["A", "B", "E", "C", "D"]
var copy = example.splice(2, 1); // remove 1 item at 2-index postion, return the deleted item

console.log(copy);
// ["E"]
console.log(example);
// ["A", "B", "C", "D"]
var copy2 = example.splice(2, 0, 'E');

console.log(copy2);
// []
console.log(example);
// ["A", "B", "E", "C", "D"]
Enter fullscreen mode Exit fullscreen mode

Example : simulate shift() with splice()

function shiftArray(arr) {
  // remove 1 item at 0-index position, return the deleted item 
  return arr.splice(0, 1); 
}

var a = [1, 2, 3];

var b = a.shift();

console.log(a); // [2, 3]

console.log(b); // 1

var c = shiftArray(a);

console.log(a); // [3]

console.log(c); // [2]
Enter fullscreen mode Exit fullscreen mode

begin ( option )

  • undefined: slice begins from index 0

  • >= 0: zero-based index before which to begin

  • < 0: an offset from the end of the sequence

end ( option )

  • undefined: extracts through the end of the sequence

  • >= 0: zero-based index before which to end

  • < 0: an offset from the end of the sequence

var arr = ['A', 'B', 'C', 'D'];

var a = arr.slice();        // begin is undefined, slice begins from index 0 to the length of array.

console.log(a);
// ["A", "B", "C", "D"]
var b = arr.slice(-1);      // begin is negative 1, slice begins from the last one element to the length of array. 

console.log(b);
// ["D"]
var c = arr.slice(0, -1);   // begin is zero, slice begins from index 0 to the first-to-last element. 

console.log(c)
// ["A", "B", "C"]
Enter fullscreen mode Exit fullscreen mode

_Example _: convert Array-like objects / collections to a new Array

function convert2Array() {
  return Array.prototype.slice.call(arguments);
}

var arr = convert2Array(1, 2, 3); 

console.log(arr)
// [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Slice

slice() is a method of Array Object and String Object. It is non-destructive since it return a new copy and it doesn’t change the content of input array. slice() is normally used in function programming to avoid side-effect.

Array.prototype.slice()
Enter fullscreen mode Exit fullscreen mode

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end ( end is not included ). The original array will not be modified.

String.prototype.slice()
Enter fullscreen mode Exit fullscreen mode

The slice() method extracts a section of a string and return it as new string.

array.slice(begin, end)
string.slice(begin, end)
Enter fullscreen mode Exit fullscreen mode
var a = ['A', 'B', 'C', 'D'];

var slicedArr = a.slice(1, 3);  // slice starts from 1-index to 3-index, but not include 3-index : ['B', 'C']

console.log(a)
// ["A", "B", "C", "D"]         // slice doesn't change the input
console.log(slicedArr)
// ["B", "C"]
var b = 'ABCD'

var slicedStr = b.slice(1, 3);  // slice process the slice as the array

console.log(b)
// "ABCD"
console.log(slicedStr)
// "BC"
Enter fullscreen mode Exit fullscreen mode

If you want to dig deeper or you haven't really got it yet I highly recommend to check out the articel Slice and splice: explained from @murkrage.

Split

split() is a method of String Object. It splits a string by separator into a new array.

String.prototype.split()
Enter fullscreen mode Exit fullscreen mode

The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.

string.split([separator[, limit]])
Enter fullscreen mode Exit fullscreen mode
var string = 'Hello World. How are you doing?';

var splits = string.split(' ', 3);    // split() looks for spaces in a string and returns the first 3 splits that it finds. 

console.log(splits)
// ["Hello", "World.", "How"]
var splits = string.split(' ')

console.log(splits)
// ["Hello", "World.", "How", "are", "you", "doing?"]
Enter fullscreen mode Exit fullscreen mode

Example : check if the string is palindrome.

var str = "abcba";

function isPalindrome(str) {
  // split the string to array, reverse the array, then join the array with ''
  return str === str.split('').reverse().join(''); 
}

isPalindrome(str); // return true
Enter fullscreen mode Exit fullscreen mode

Conclusion

Splice, Slice, Split

Splice() is used to add or remove an element in a array, and it would modify the origin array. Slice() is used to extract elements from an array and return a new array, and it would not modify the origin array. Split() is used to convert the input string into an array by the separator, and since string is immutable, it would not modify the origin string. Be careful when using splice because it might cause side-effect.

If you want to learn more about working with strings I highly recommend you to read the article Javascript : Dealing with strings from @rawan_amr_abdulsattar.

*That’s it and if you found this article helpful, please hit the ❤️, 🦄 button and share the article, so that others can find it easily :) *

If you want to see more of this content you can support me on Patreon!

Have a nice day!

Top comments (0)