javascript - 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?
解决方案
您可以像这样使用捕获组:
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)
推荐阅读
- c - for循环中的N模0返回C中的N?
- c# - 搜索文档 elasticsearch ,包含长字段子值的字段
- xamarin - 使用自定义文本样式时 Xamarin 应用程序崩溃
- javascript - 使用 JavaScript 对象动态填充 HTML
- html - 无法让“位置:粘性”在我的导航栏上工作。任何帮助表示赞赏
- algorithm - 给定一个矩形的 4 个点(具有某种旋转),确定一个点是否在矩形内
- asp.net - ASP.NET CheckBox 总是返回 false 值
- css - 在引导程序 4 中更改刷新列表换行符的颜色
- javascript - 在反应中创建一个类函数
- algorithm - 找到具有 2 个条件的 NFA