简体   繁体   English

用于检查字符串是否包含“`”字符的正则表达式

[英]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.

相关问题 检查字符串是否在javascript中包含任何特殊字符或字符串 - checking whether a string contains any special character or string in javascript Javascript:检查字符串是否包含字符,然后删除字符串的一部分? - Javascript: Checking if string contains a character, then removing part of a string? 检查element是否包含字符串,仅包含字符串-可能是正则表达式 - Checking if element contains a string, and nothing but a string - maybe regex 检查字符串是否包含字符序列和javascript中的未知变量? - Checking if a string contains character sequence and unknown variable in javascript? 用于检查字符串是否包含有效脚本标记的正则表达式 - Regex expression for checking if a string contains a valid script tag 最有效的正则表达式,用于检查字符串是否包含至少3个字母数字字符 - Most efficient regex for checking if a string contains at least 3 alphanumeric characters 正则表达式 - 如何排除包含特定字符的特定字符串 - Regex - how to exclude a specific string that contains a specific character jQuery RegEx。 如果string包含除以外的任何字符 - jQuery RegEx. If string contains any character except 如何编写正则表达式来检查字符串是否包含特殊字符和多个空格 - How to write regex to check if a string contains special character and multiple whitespaces 检查字符串是否包含图像 - Checking if a string contains a image
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM