split string by text in javascript

How to Split String By Particular Character

JavaScript provides many powerful functions to work with strings and text. Often developers need to split a string by space into an array of substrings. Sometimes you may need to split string breaking at particular character. In this article, we will learn how to split string by particular character.


How to Split String By Particular Character

Here are the steps to split string by particular character. Generally people split a sentence into words by splitting it by whitespace characters. But sometimes you may need to split your text by a custom character. Let us say you have the following string.

var input = 'john smith$123 Street$Apt 42$New York$NY$12345';

Let us say you want to split the above text by character ‘$’ instead of space. You can do easily do this using split() function available for each string, out of the box. Here is the command to split the above text by $ sign.

var words = input.split('$');

The above command will split the string into an array of substrings and store it in words variable.

['john smith','123 Street','Apt 42','New York','NY','12345']

Once you have split the string into an array of substrings, you can access individual substrings using the array name and index.

var name = words[0]; //john smith
var street = words[1]; //123 Street
...

If you don’t specify the character for splitting in split() function, it will split your string by space character, by default.

In this article, we have learnt how to split string by character using JavaScript. This is useful especially if you want to parse data into manageable chunks of information. Many times, during data transfer across applications, some of the delimiters are replaced by custom strings making it difficult to parse them. In such cases you can split them as shown above.

Also read:

How to Read Local Text File in Web Browser Using JavaScript
How to Encode String to Base64 in JavaScript
How to Get Length of JavaScript Object
How to Get Client IP Address Using JavaScript
How to Break ForEach Loop in JavaScript

Leave a Reply

Your email address will not be published.