0

I want to fetch the text between ** and **.

This is what I am trying with:

/\**(.*)\**/ig

This is the sample string

** The ** *quick* ~~brown~~ fox ** jumped **

please ignore the space after ** and before **

As a result, I am getting the whole string fetched

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
Siddharth Thakor
  • 156
  • 3
  • 17
  • 3
    Try replacing `/\**(.*)\**/ig` with `/\*\*(.*)\*\*/ig` (so a backslash before each *, as you are trying to fetch the literal * symbol twice) – elveti Jun 13 '19 at 14:21
  • are you trying to find from markdown text ?, try this [`regex`](https://regex101.com/r/n8lQ1k/1) – Kunal Mukherjee Jun 13 '19 at 14:21
  • I want to fetch text between ** and ** from the string (Which comes from API response) and bold the detected string and update the GUI – Siddharth Thakor Jun 13 '19 at 14:25
  • is it not already bold in markdown format ? – Kunal Mukherjee Jun 13 '19 at 14:26
  • No, it is not!!! – Siddharth Thakor Jun 13 '19 at 14:29
  • Try `\*\*[\w]+\*\*`. It's a simpler example. Test it here https://regex101.com/r/M2xp0B/1/ – GRoutar Jun 13 '19 at 14:31
  • The marked duplicate question doesn't really address your central problem of the fact that you can't match all the instances of bold text, but without the *'s. This is because JS doesn't support the combination of the global `g` flag and matched sub-groups in the resultant array. It also doesn't support look-behind assertions, both of which would make your task easier. One trick is iterative `replace()` with a callback. [Fiddle](https://jsfiddle.net/syb56j3q/) – Mitya Jun 13 '19 at 14:32

1 Answers1

3

I'm a bit surprised your regex doesn't blow up with a compile issue since asterisk is a special character - it means 'zero or more' of whatever was previous. Based on your regex, you are capturing:

* zero or more of (nothing)
* zero or more of (nothing)
(.) any single character (in a capturing group)
* zero or more of (the previous item, 'any character')

What you want is, I think:

/\*\*(.*?)\*\*/ig

Thats:

\* the asterisk character
\* another asterisk
(.*?) anything, non-greedy (up until whatever is next in the regex)
\* the asterisk character
\* another asterisk
josh.trow
  • 4,861
  • 20
  • 31
  • 1
    It doesn't blow up because `\**` means that it will try to match 0 or more asterisk characters. – Silviu Burcea Jun 13 '19 at 14:27
  • Keep in mind that this answer also matches the text between more than two asterisks. For example in the string `"***text between triple asterisks***"` it will match `"**text between triple asterisks**"` with group 1 being `"text between triple asterisks"`. – 3limin4t0r Jun 13 '19 at 15:15
  • @SilviuBurcea the original question had some missing formatting, so I couldn't see the leading backslash - it makes much more sense now why it was at least running – josh.trow Jun 21 '19 at 13:42