[英]Regex for checking if a string contains "`" character
I'm trying to check if a string contains this character `
.我正在尝试检查字符串是否包含此字符
`
。
And if the character is found, to wrap that string between <div>
.如果找到该字符,则将该字符串包裹在
<div>
之间。
For example:例如:
`this is it
should become:应该变成:
<div>this is it</div>
And I've tried to do it but it seem to not work:我试过这样做,但似乎不起作用:
let arr = "`this is it";
if (arr.includes('`')) {
arr = arr.replace(/\`(\w+)\`/g, '<div>$1</div>');
}
Any ideas?有任何想法吗?
You can use您可以使用
arr.replace(/`([^`]+)`?/g, '<div>$1</div>')
The regex matches正则表达式匹配
`
- a backtick `
- 反引号([^`]+)
- one or more chars other than backtick ([^`]+)
- 除反引号外的一个或多个字符`?
- an optional backtick JavaScript demo JavaScript 演示
const arrs = ["`test` is `here`","`this is it"]; const regex = /`([^`]+)`?/g; for (const arr of arrs) { console.log(arr, '=>', arr.replace(regex, '<div>$1</div>')); }
I presume that the backtick should only appear at the beginning of the line.我认为反引号应该只出现在行首。 If it is also needed at the end, add another one before the
$
in the regex.如果最后还需要,请在正则表达式中的
$
之前添加另一个。
I also presume that your string is multiline, and any line can start with a backtick.我还假设您的字符串是多行的,并且任何行都可以以反引号开头。 If not, remove the
m
flag.如果没有,请删除
m
标志。
If there can be more than one backtick-delimited substrings in a line, make the *
quantifier non-greedy with ?
如果可以在一行超过一个反引号分隔字符串,使
*
量词非贪婪与?
and remove the ^
and $
assertions.并删除
^
和$
断言。 If such substring can span several lines, also add s
flag.如果这样的子字符串可以跨越多行,还要添加
s
标志。
let arr = "`this is it"; arr = arr.replace(/^`(.+)$/mg, '<div>$1</div>'); console.log(arr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.