Hello World

JavaScript String Split Example 본문

Javascript/Tips

JavaScript String Split Example

EnterKey 2016. 1. 10. 13:33
반응형

The split() method

You can split a string using the split() method. It takes a delimiter as a variable, which can be either a comma, a semicolon, a quotation mark, or whatever special character that is used to separate the string. You can use it like this:

1var namelist = "Anne,Ben,Cindy,Diane,Era ";
2 
3var nameArray = namelist.split(',');

First, we have declared a string variable which contains some random names (you can use whatever string you want). Then we used the split() method on the string, by placing a comma as a delimiter. That means that the string will be divided into one more string than the number of the commas, and these will be respectively the strings before and after each comma. The result of the previous example will be this:

1nameArray=['Anne','Ben','Cindy','Diane','Era'];

The delimiter argument to this method is optional, which means that if you leave it blank, the method will split the string after it finds a NULL character. Practically, it means that your string will not be divided.

The join() method

What is often called the reverse of the split() method is the join() method. It is used to put together into one single string the elements of an array, using a delimiter as a joint. The code snippet below will show you how exactly it is used:

1var array = ['This','is','an','apple.'];
2 
3var sentence= array.join(' ');

We have declared and given string values to an array, and then used the join() method on this array to turn it into a single string, using a blank space as a joint.
The result will be this:

1sentence="This is an apple.";

If you omit the joint character in this method, a comma will be used instead.

This is how you split or join strings using JavaScript.

Download the source code

This was an example of string split in JavaScript.

Download
Download the full source code of this example here: StringSplit


반응형

'Javascript > Tips' 카테고리의 다른 글

throttle과 debounce  (0) 2016.05.04
자바스크립트를 이용한 CSV 파일 파싱  (0) 2016.05.04
gulp 소개  (0) 2016.01.10
Javascript 면접 문제  (0) 2016.01.10
javascript로 버튼에 print 링크 다는 방법!  (0) 2012.11.19
Comments