Home >Web Front-end >JS Tutorial >How Can I Split a String Using Multiple Separators in JavaScript?
Splitting Strings with Multiple Separators in JavaScript
JavaScript's split() function may seem to offer only one separator option, making it difficult to split on multiple delimiters. However, there's a hidden gem.
Solution:
The secret lies in using a regular expression as the separator parameter. A regular expression, such as [s,] , can represent multiple whitespace and comma characters. By using this regexp, you can split the string on both delimiters:
"Hello awesome, world!".split(/[\s,]+/)
This will return an array of split strings:
["Hello", "awesome", "world!"]
Additional Notes:
To extract the last element of the array, use:
let bits = "Hello awesome, world!".split(/[\s,]+/) let lastBit = bits[bits.length - 1] // "world!"
If the pattern doesn't match, you'll get a single element in the array:
bits = "Hello awesome, world!".split(/foo/) console.log(bits[bits.length - 1]); // "Hello awesome, world!"
So, whether you're trying to split on commas, spaces, or a combination of characters, you now have the solution at your fingertips.
The above is the detailed content of How Can I Split a String Using Multiple Separators in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!