+ 1

[SOLVED] About split() Function

In split function we can pass a string and break our original string as well as we find our output as arrays. But how can I break my original string into multiple places using split() function? Can we pass multiple string through our split function that can break our original string for multiple strings. In the code I pass split(",") and check the output it takes my semicolon into another entry of an array together. I want it also break for ";" too. A show both in seperated entry. https://sololearn.com/compiler-playground/cekZcsTy75Zr/?ref=app

1st May 2024, 6:29 PM
`ᴴᵗᵗየ
`ᴴᵗᵗየ - avatar
2 Antworten
+ 9
My JS skill is below average, but I searched out the answer. You can pass a regular expression into split() that defines multiple delimiters. const re = new RegExp("[, ;]"); const sHop = list.split(re); The square brackets in RE syntax indicate to search for any one of the enclosed items. To consolidate consecutive delimiters and prevent extra blank strings, add a "+" like this "[, ;]+", which searches for 1 or more consecutive tokens. There is a shorter syntax to define an embedded regular expression. Enclose the expression between forward slash marks. This is the preferred way to do it: const sHop = list.split(/[, ;]+/); Since your test string ends with space, maybe a trim would be good, too. const list = "customerID, Name; Age "; const sHop = list.trim().split(/[, ;]+/);
1st May 2024, 8:22 PM
Brian
Brian - avatar
+ 2
Thanks Brian brother for your clear explanations.
2nd May 2024, 3:49 AM
`ᴴᵗᵗየ
`ᴴᵗᵗየ - avatar