Home

Ways to Split strings in JavaScript

The split method on the string prototype is used to split strings in JavaScript. The general syntax of the split method is

str.split([separator[, limit]])

The separator(string or regex) is the where the split should occur. The limit(positive integer) is number of entries needed after the split.

The split method will always returns an array.

The following are the different examples that use split method:

const message = "Hello World"
const nullString = ""

console.log(message.split()) // Output → ["Hello World"]
console.log(message.split("")) // Output → ["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"]
console.log(message.split(" ")) // Output → ["Hello", "World"]

console.log(nullString.split()) // Output → [""]
console.log(nullString.split("")) // Output → []
const review = "John → AWSM is awesome!!!"

console.log(review.split(" → ")) // Output → ["John", "AWSM is awesome!!!"]
console.log(review.split("!")) // Output → ["John → AWSM is awesome", "", "", ""]
console.log(review.split("!!")) // Output → ["John → AWSM is awesome", "!"]

If you want to just remove the special characters from the above string you need to use a regex or replace method.

str.replace(/[^a-zA-Z0-9\s]+/g, "")

Using regex

const str = "A string with numbers 1, 2 and 3."
console.log(str.split(/(\d)/))
// Output → ["A string with numbers ", "1", ", ", "2", " and ", "3", "."]

Note: \d matches the character class for digits between 0 and 9.

Using limit

In the above review example, if you are interested in getting the name("John") from the review you can use limit to get only 1 entry in the output.

const review = "John → AWSM is awesome!!!"

// With Limit
console.log(review.split(" → ",1)) // Output → ["John"]

// Without Limit
console.log(review.split(" → ")) // Output → ["John", "AWSM is awesome!!!"]


Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →

Comments