wyc
wyc

Reputation: 55263

How to replace characters at the beginning and at the end of a word?

For example:

var string = This is a *piece* of text.

I could do:

string.replace(/\*/g, <em>)

However, I would get this: <em>piece<em>. And what I want to get is this: <em>piece</em>.

How to modify this code so I can detect the * character at the beginning and end of a word?

Upvotes: 0

Views: 114

Answers (2)

maioman
maioman

Reputation: 18734

You can use capturing groups like this:

var string = 'This is a *piece* of text.'

var r = string.replace(/\*([^\*]+)\*/, (m, m1) =>
  `<em>${m1}</em>`)

console.log(r)

Even better you could build regex on the fly with any boundry character

const parseChar = x => node => str => {
  const re = new RegExp(`\\${x}([^\\${x}]+)\\${x}`)
  return str.replace(re, (_, m) =>
    `<${node}>${m}</${node}>`
  )
}

 var string = 'This is a *piece* of text.'
 
 var r = parseChar('*')('em')(string)
 
 console.log(r)

Upvotes: 4

The fourth bird
The fourth bird

Reputation: 163217

You could use replace with a first capturing group where you would capture not a * using a negated character class ([^*]+) and use the g global flag to replace all of them.

\*([^*]+)\*

That would match

  • \* Match *
  • ([^*]+) Capture in a group matching not a * one or more times or else you might end up with <em></em>
  • \* Match *

var string = 'This is a *piece* of text and *piece*';
string = string.replace(/\*([^*]+)\*/g, "<em>$1</em>");
console.log(string);

Upvotes: 4

Related Questions