我正在努力实现:
const finalStr = "team='Core', team='Mechanics'"
//loop through string, get single quotes, add <bold>'Core'</bold>
//I want to return the string:
"team=<bold>'Core'</bold>, team=<bold>'Mechanics'</bold>"
我尝试过的方法,但显然是错误的......我无法理解它:
const finalStr = this.state.finalString
const newFinal = finalStr.match(/'(.*?)'/g).map(item => {
item = item.replace(item, '<b>' + item + '</b>')
return item;
});
最佳答案
您不需要回调或任何其他功能,只需使用 replacement pattern
在 String.replace()
中描述文档插入匹配的子字符串 ( $&
)。除非您打算对匹配项执行其他操作,否则您也不需要捕获组的括号。
const finalStr = "team='Core', team='Mechanics'"
const newFinal = finalStr.replace(/'.*?'/g, '<bold>$&</bold>')
console.log(newFinal)
作为旁注,没有 <bold>
HTML 中的标记,因此如果您尝试创建有效的 HTML,您应该使用 <b>
.
关于javascript - 如何循环遍历正则表达式匹配的字符串,concat 返回新的完整字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53289446/