How to split string after specific character in JavaScript

In this post, we will learn how to split a given string at a specific character in JavaScript.

To split a string after a specific character we can use the split() method on the string in JavaScript that takes the character as an argument and returns an array containing the substrings.

Split string at a specific Character

The split() method in JavaScript is used to split a string into an array of substrings. This method returns a new array and does not change the original string.

Syntax:

string.split(seperator)

seperator – Any string or regular expression used for splitting the string.

Let’s see an example to split the string at the dash (-) character.

let str = "Hello-how-are-you"

const splitArr = str.split("-") 
console.log(splitArr)

Output:

[ 'Hello', 'how', 'are', 'you' ]

Here, we have applied the split() method on the string and passed the special character, here dash (-) as the argument to split the string whenever it encounters the character.

Once done, it returns us the array of substrings as the output.


FAQ

How to remove everything after space in Javascript

To remove everything after space from a string in Javascript, we have to use the split() method and return the first item from the array.

Example:

const str = "Batman Superman"

console.log(str.split(" ")[0]) // Batman

The split() method with the " " as separator returns the array of substring and from there we extract the 0 index item i.e here is Batman.


Related Topics:

Split a String in N chunks into an array in JavaScript

Replace all occurrences of a string in JavaScript

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top