繁体   English   中英

如何替换块/段之前和之后的字符?

[英]How to replace characters that are before and after a block/paragraph?

这是我在单词前后替换字符的方法:

el = el.replace(/"\b/g, '“')
el = el.replace(/\b"/g, '”')

如果我想转此怎么办:

```
This is a quote
```

进入这个?

<quote>
This is a quote
</quote>

你可以匹配

^```

,懒惰重复任何角色,直到你到达另一个角色

^```

开头的^确保三个反引号位于一行的开头,下面的[\\s\\S]是一种匹配任何字符的方法 ,包括换行符. 默认情况下不会这样做:

 function doReplace(str) { console.log(str); console.log( str.replace(/^```([\\s\\S]*?)^```/gm, '<quote>$1</quote>') ); } doReplace("```\\nThis is a quote\\n```"); doReplace("```\\nThis is a quote\\nand there are some backticks in the text\\nbut not ``` at the beginning of a line\\n```"); 

这可能是另一种方法,分别将起始和结束三重反向勾选“``”替换为<quote></quote>

 const string = "```\\nThis is a quote\\n```"; const replacer = { '```\\n': '<quote>\\n', '\\n```': '\\n</quote>' } const str = string.replace(/```\\n|\\n```/gm, function(matched) { return replacer[matched]; }) console.log(str); 

暂无
暂无

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

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