TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVASCRIPT

JavaScript split Examples

Separate parts from a string with the split function. Split on characters, strings and patterns.
Split. Consider a string that has many parts. It has a delimiter character that we want to split upon. With split() in JavaScript we have many ways to do this.
Often, the best approach is the simplest. With a single character delimiter, we can write simple code to split the string. Sometimes a regular expression is needed.
First example. Here we introduce a string literal that has 4 substring separated with a plus delimiter. The "plus" character separates 4 color names.Strings

Part 1: We call the split method with a one-character string argument: the "+" char.

Part 2: The array returned has 4 strings in it—the plus separates each string so there are fewer delimiters than strings.

Part 3: We loop over the array returned from the split method. It has 4 elements, one string for each color word.

Array
JavaScript program that uses split var colors = "blue+orange+red+yellow"; // Part 1: split on the plus. var result = colors.split("+"); // Part 2: write the length. console.log("SPLIT RESULT LENGTH: " + result.length); // Part 3: write each resulting string. for (var i = 0; i < result.length; i++) { console.log("SPLIT RESULT: " + result[i]); } Output SPLIT RESULT LENGTH: 4 SPLIT RESULT: blue SPLIT RESULT: orange SPLIT RESULT: red SPLIT RESULT: yellow
Regex. Sometimes we need a more complex approach to separating strings. We can use a regular expression. Here we split on one or more non-word characters (like spaces or newlines).

Tip: With a regular expression, we can treat multiple delimiters as a single one. This eliminates empty entries.

JavaScript program that uses split, regex var data = "cat bird frog"; // Split on one or more non-word characters. // ... This includes spaces and newlines. var results = data.split(/\W+/); console.log("SPLIT NON-WORD: " + results); Output SPLIT NON-WORD: cat,bird,frog Regex description: \W non-word character + one or more
Get numbers. With split() and a regular expression we can get the numbers from a string. We split on non-digit characters. The uppercase "D+" means one or more non-digit chars.

Tip: To extract numbers, we can split on "not number" characters. Then we use Number() to convert the strings to actual numeric values.

Tip 2: Split is a good choice for parsing simple data strings. In JavaScript we often have better performance with fewer statements.

JavaScript program that gets numbers from string var input = "0 cat 10(20)30-500"; // Split on no none or more non-digit chars. var numberStrings = input.split(/\D+/); // Convert all strings into Numbers. // ... Write them. for (var i = 0; i < numberStrings.length; i++) { var number = Number(numberStrings[i]); console.log("NUMBER: " + number); } Output NUMBER: 0 NUMBER: 10 NUMBER: 20 NUMBER: 30 NUMBER: 500 Regex description: \D+ one or more non-digit characters
Character set. We can split on a set of characters—here we have 3 char delimiters, and we split a string on all of them in a single call. We use a character set in the regular expression.

Tip: Be careful to escape metacharacters in the regex. If the pattern does not work, try escaping some characters with the backslash.

JavaScript program that uses split, set of characters // This string has multiple delimiter chars. var codes = "100x200y300z400"; // Split on a set of characters at once. var results = codes.split(/[xyz]/); // Display results. for (var i = 0; i < results.length; i++) { console.log("RESULT: " + results[i]); } Output RESULT: 100 RESULT: 200 RESULT: 300 RESULT: 400 Regex description: [xyz] the character x, y, or z
Benchmark. Split() takes more time to handle more complex delimiter patterns. Here we time split on a single-char space. We compare this to splitting on non-word characters.

Version 1: This version of the code splits the input string in a tight loop on the space character.

Version 2: The code splits the input string with a non-word character—this is a character class.

Result: In 2019, splitting on a regular expression in Chromium appears to be faster than splitting on a string.

JavaScript program that times split on character var result = 0; var words = "bird frog fish"; var x1 = performance.now(); // Version 1: split on a string. for (var i = 0; i < 10000000; i++) { var array = words.split(" "); result += array.length; } var x2 = performance.now(); // Version 2: split on a non-word character. for (var i = 0; i < 10000000; i++) { var array = words.split(/\W/); result += array.length; } var x3 = performance.now(); // Results. console.log("TIME 1: " + (x2 - x1)); console.log("TIME 2: " + (x3 - x2)); Output TIME 1 (2019): 1675.900 TIME 2: 1433.450
Split cache. In modern browsers we find a "split cache." The results of a split() call are cached in the JavaScript engine memory so they can be used again.

So: If we call split() with the same strings many times, this will execute quickly. Chromium V8 first implemented this optimization.

Cache String.prototype.split: mozilla.org

Note: In my testing, avoiding the overhead of split on the first call is still better for performance. The array is a faster syntax.

Split cache: Optimize the common obfuscator pattern where ["foo","bar","baz"] gets converted fo "foo,bar,baz".split(",").
A review. Splitting a string is a common operation in nearly all languages. In JavaScript it has special optimizations, but the logic is recognized from other languages.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf