Javascript Introduction - Splitting a String

Guest Posts Paolo Nikko Nuñal

Splitting a string is used by many programmers in manipulating data. This is important for data that needs to be filtered out and that of those being returned by a specific function. In this tutorial, you are going to learn how to split() a string.

The split() method is used to split a string into an array of substrings, and returns them into a new array.




Learn HTML5/PHP/AJAX Web Programming from Scratch – An amazing course from Dr. Richard Stibbard. Usually I only promote my own courses, but this course is very impressive, so I cut a deal with Dr. Stibbard … You can also find Richard’s website here





Split

[String].split([seperator],[limit])

seperator - This is optional, this specifies the character, or the regular expression of the string. If this is omitted, the new string will be returned with only a single item containing it.

limit - This is optional. You need to enter an integer, that specifies the number of splits it is going to create, items after the split limit will not be included.

Code


<html>
<body>
<p id="text">I am a text to be splitted</p>
<button onclick="splitText()">Split Me</button>

<script>
function splitText()
{
var text = "I am a text to be splitted";
var res  = text.split(" ");
alert(res);
document.getElementById("text").innerHTML=res;
}
</script>
</body>
</html>


Based from the example above, we have split the text by spaces. You can see from the split() that we have the parameter " " that tells the split method to split text if it founds a white space.

Code


<html>
<body>
<p id="text">Theoquickobrownofoxojumps</p>
<button onclick="splitText()">Split Me</button>

<script>
function splitText()
{
var text = "I am a text to be splitted";
var res  = text.split(" ");
alert(res);
document.getElementById("text").innerHTML=res;
}
</script>
</body>
</html>


In the last example, we have split the text based on the letter "o". Always remember that the results will be placed into an array and that each split word / letter are store inside a separate array index.

For more tutorials you can check out the courses from Dr. Richard Stibbard.




Learn HTML5/PHP/AJAX Web Programming from Scratch – An amazing course from Dr. Richard Stibbard. Usually I only promote my own courses, but this course is very impressive, so I cut a deal with Dr. Stibbard … You can also find Richard’s website here