How to split string after specific character in JavaScript

featured Image

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

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more

Leave a Reply

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