Should be trivial but I’ve struggled over this simple issue:
Example string:
#anchor1: text including special chars like % #anchor2:text has # char
should get splitted in:
[#anchor1: text including special chars like %]
[#anchor2:text has # char]
anchors have always a hash followed by any character followed by a colon.
I’ve tried #\S+:[^#+] but this stops at the # inside anchor2
>Solution :
ChatGPT says:
Hey! To split the string into an array using the given pattern, you can use JavaScript’s str.match method with the appropriate regex pattern. The regex pattern should look for a sequence that starts with #, followed by any characters, and ending with a :. Then it should capture everything until the next sequence that matches the pattern.
Here’s a quick code snippet to do that:
const str = "#anchor1: text including special chars like % #anchor2:text has # char";
const regex = /(#\w+:.*?)(?=#\w+:|$)/g;
const result = str.match(regex);
console.log(result);
This will output:
[ '#anchor1: text including special chars like % ', '#anchor2:text has # char' ]
Hope this helps! Let me know if you have more questions.