I'm trying to split a string into a stack/array of string based on a regex match. The string can have Remix Icon embedded in it, that I'll extract and render HTML attributes based on the positioning.
Objective
The icon names will be wrapped by :
before and after. The objective is to split strings like so:
"Select an option:ri-arrow-down-s-line:"
--->["Select an option", ":ri-arrow-down-s-line:"]
"Download :ri-download-line: or upload :ri-upload-line:"
--->["Download ", ":ri-download-line:", " or upload ", ":ri-upload-line:"]
":ri-download-line:"
--->[":ri-download-line:"]
What's happening
I tried using this.label.split(/:ri-.*:/)
but it doesn't include the icon names in the result stack and doesn't work with repetitions. Something like "Download :ri-download-line: or upload :ri-upload-line:" gives an output of ['Download ', '']
with this.
- Improvement 1: Using
/:ri-[^:]*:/
improves the string splitting, and accounts for repetitions. However now I need to figure out how to include the matched regex in the stack at the respective positions
Can someone please point me to the right direction?
CodePudding user response:
You can use this simple refex to do the splitting:
/(?=:ri)/g
It simply splits whenever there's :ri
to the right.
Note it uses the global
flag so it can match and split on all occurences.
Now you have an array. If you want the syntax shown in your question, you can use JSON.stringify
on the result.
CodePudding user response:
You might use capturing group in split /(:ri-[^:] :)/
to be included into the result, then you might have to filter empty elements from the split result:
const Split = s => s.split(/(:ri-[^:] :)/).filter(Boolean);
console.log(Split("Select an option:ri-arrow-down-s-line:"))
console.log(Split("Download :ri-download-line: or upload :ri-upload-line:"))
console.log(Split(":ri-download-line:"))
CodePudding user response:
Instead of splitting on 1, it could be matching both.
For example:
const label = "Download :ri-download-line: or upload :ri-upload-line:"
let arr = label.match(/(:ri-[^:]*:)|[^:] /g);
console.log(arr);