简体   繁体   English

如何在单词的开头和结尾替换字符?

[英]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> . 但是,我会得到这个: <em>piece<em> And what I want to get is this: <em>piece</em> . 我想得到的是: <em>piece</em>

How to modify this code so I can detect the * character at the beginning and end of a word? 如何修改此代码,以便我可以在单词的开头和结尾检测*字符?

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) 

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. 您可以将replace与第一个捕获组一起使用,在该捕获组中,您不会使用否定的字符类([^*]+)捕获*,并使用g全局标志替换所有它们。

\\*([^*]+)\\*

That would match 那会匹配

  • \\* Match * \\*匹配*
  • ([^*]+) Capture in a group matching not a * one or more times or else you might end up with <em></em> ([^*]+)捕获一次或多次不匹配的组,否则您可能会得到<em></em>
  • \\* Match * \\*匹配*

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM