Improve Article
Save Article
Like Article
Given a statement which contains the string and separators, the task is to split the string into substring. Syntax: Parameters: This function accepts three parameters as mentioned above and described below: Array join() function: The Array.join() function is used to join the elements of the array together into a string. This method adds the elements of an array into a string and returns the newly created string. The elements separates by a specific separator. Default separator used is comma (, ). Syntax: Parameters: This function accepts two parameters as mentioned above and described below: Example 1: This example splits a string by 2 separators Comma(, ) and space(‘ ‘) using .split() function. <!DOCTYPE html> <html> <head> <title> JavaScript | Split a string with multiple separators. </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id="GFG_UP" style="font-size:18px; font-weight:bold;"></p> <button title = "gfg_Run()"> split </button> <p id="GFG_DOWN" style="font-size:25px; font-weight:bold;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "A, computer science, portal!"; el_up.innerHTML = str; function gfg_Run() { var arr = str.split(/[\s, ]+/) el_down.innerHTML = arr; } </script> </body> </html>
String split() Method: The str.split() function is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument.
Output:
- Before clicking on the button:
- After clicking on the button:
Example 2: This example split the string by number of separators like Comma(, ), equal(=) and colon(:) using multiple .join() and .split() method.
<!DOCTYPE html> <html> <head> <title> JavaScript | Split a string with multiple separators. </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 18px; font-weight: bold;"> </p> <button title = "gfg_Run()"> split </button> <p id = "GFG_DOWN" style = "font-size: 25px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var str = "A, computer=science:portal!"; el_up.innerHTML = str; function gfg_Run(){ var arr = str.split('=').join(', ').split(':').join(', ').split(', '); el_down.innerHTML = arr; } </script> </body> </html> |
Output:
- Before clicking on the button:
- After clicking on the button: