问题描述
我想检测单词中的@
字符并在单词周围添加跨度。我的输出采用以下格式:
<p class="comments">Where is @james? I hope him and @elaine are okay.</p>
我希望它成为:
<p class="comments">Where is <span>@james</span>? I hope him and <span>@elaine</span> are okay.</p>
我这样做的目的是要对名称进行样式设置。我正在寻找reactjs
解决方案,但是如果有CSS方法,那也可以。
解决方法
您可以使用正则表达式/(@[a-z0-9]*)/gi
来匹配并包含@
和单词,以及string :: replace以用跨距换行。
在这里,/(@[a-z0-9]*)/gi
对仅 包含字母a到z和数字的单词进行不区分大小写的全局搜索,但是如果要包装的单词可以调整可以包含其他字符。
string.replace(regex,'<span>$1</span>')
正在调用正则表达式来搜索和替换找到的捕获匹配项(即跨度中的$1
)。
const regex = /(@[a-z0-9]*)/gi;
const string = 'Where is @james? I hope him and @elaine are okay.';
console.log(string.replace(regex,'<span>$1</span>'));
当然,这只会给您一个带有"<span>"
文字的字符串,因此要将 actually 呈现为html,可以使用react dangerouslySetInnerHTML,因此您可以将以上内容提取到实用程序功能中
const formatAts = text => {
const regex = /(@[a-z0-9]*)/gi;
return text.replace(regex,'<span>$1</span>');
}
并在JSX中使用
<p
class="comments"
dangerouslySetInnerHTML={
formatAts('Where is @james? I hope him and @elaine are okay.')
}
/>
,
您可以将注释/文本拆分为regrexp为[文本,用户等...]的数组,然后使用map对其进行重构,同时遍历数组可以检查字符串是否以'@'开头,如果是,则将字符串包装在span标签中
import React from 'react';
export default ({ comment = 'random text @username more random @username2 text asdsad'}) => {
function pipeDecorateUsername(text) {
// took pattern from Drew Reese answer
const regexpPattern = /(@[a-z0-9\-\_]*)/gi;
// split text into components/strings as [text...,username,etc...]
const textComponents = text.split(regexpPattern)
return (
<>
{textComponents.map(component => {
/**
* wrap username in span
*/
if(component[0] === '@') {
return (
<span style={{color: 'green'}}>{component}</span>
)
}
else {
return component;
}
})}
</>
)
}
return (
<div>
{pipeDecorateUsername(comment)}
</div>
)
}