Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get javascript regex to return everything in the string as part of the matches, not just the matched parts

Test string:

*This* is a test.[15] I would like[16] To figure _out how_ to do this.[20]

RegEx:

/\[\d+\]|\*.*\*|_.*_/gu

Actual Results:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Match 1: *This*
Match 2: [15]
Match 3: [16]
Match 4: _out how_
Match 5: [20]

Desired Results:

Match 1: *This*
Match 2:  is a test.
Match 3: [15]
Match 4:  I would like
Match 5: [16]
Match 6:  To figure 
Match 7: _out how_
Match 8:  to do this.
Match 9: [20]

>Solution :

You may consider this approach that splits the input with capture group and uses filter to remove empty match from the start.

const s = '*This* is a test.[15] I would like[16] To figure _out how_ to do this.[20]'
console.log( s.split(/(\*[^*]*\*|_[^_]+_|\[\d+\])/).filter(Boolean) );

/*
[
  "*This*",
  " is a test.",
  "[15]",
  " I would like",
  "[16]",
  " To figure ",
  "_out how_",
  " to do this.",
  "[20]"
]
*/

RegEx Details:

  • (: Start capture group
    • \*[^*]*\*: Match substring wrapped in *
    • |: OR
    • _[^_]+_: Match substring wrapped in _
    • |: OR
    • \[\d+\]: Match [number] part
  • ): End capture group
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading