How to Split Strings in JavaScript
- 1). Open Notepad or any other text editor you prefer.
- 2). Type the following to define a string:
<html>
<script type="text/javascript">
var string = "Hello dear friends.";
The first two lines are merely HTML tags letting the web browser know that Javascript is coming. The last line creates a variable named "string" and puts some text into it. - 3). Type the following to split the string into individual words and print the result.
document.write(string.split(" "));
document.write("<p>");
The first line is made up of two commands combined. 'string.split(" ")' tells Javascript to split the string everywhere that it sees a space. This has the effect of splitting the string into individual words. The result is then sent to "document.write," which sends it to the browser.
The second line simply sends a new paragraph tag to the browser. - 4). Type the following to split the string around the fourth letter:
document.write(string.slice(0, 6));
document.write("<p>");
document.write(string.slice(6);
</script>
</html>
These are a little more sophisticated: the "slice" command, rather than splitting at set characters, cuts a string in two around a location in the string. The first line retrieves the portion of the string that runs from letter 0 to letter 6, while the next retrieves the portion starting with 6 on. - 5). Save your work with the name "splittest.html."
- 6). Double-click the file to open it in your default browser and view the results.