首页 > 解决方案 > 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?

标签: javascriptregex

解决方案


您可以像这样使用捕获组:

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

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

console.log(r)

更好的是,您可以使用任何边界字符即时构建正则表达式

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)


推荐阅读