Regex - Get formatting with no strings around [duplicate]

3

I'm trying to make a regex to get slack formatting.

Eg: *a* = > Take to make bold

An initial regex I made was:

/\*(.*?)\*/g

The problem:

  • Can not have anything around the string (No characters stuck before or after)
  • May be the beginning of the line

Situations that should work:

*a*
a *a* a

Situations that NOT should work:

b*a*
*a*b
*a**
**a*
    
asked by anonymous 11.12.2018 / 20:18

1 answer

4

1) Searching for asterisks: \*([^\*]+?)\*(?!\*)

2) Adding tags to bold: <strong>$2</strong>

Now just apply to your project:

let str = 'Lorem *ipsum dolor* sit amet, *consectetur** adipisicing elit. Optio repellat ipsa quibusdam ab doloremque accusamus nobis minima maiores voluptas, incidunt rerum alias, aliquam ut minus consequatur odio voluptatibus voluptates exercitationem.';

str = str.replace(/\*([^\*]+?)\*(?!\*)/i, '<strong>$1</strong>');

console.log(str);

@edit Now you will not find if you have two asterisks together, with nothing inside.

@ edit2 Now you will not find if you have two asterisks together at the end of the searched expression, as @ sam (% with%). And I've improved it as per the @hkotsubo tip.

  

Example working: Regex101.com

    
11.12.2018 / 20:31