简体   繁体   English

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

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

This is how I replace characters before and after a word: 这是我在单词前后替换字符的方法:

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

What if I want to turn this: 如果我想转此怎么办:

```
This is a quote
```

Into this? 进入这个?

<quote>
This is a quote
</quote>

You can match 你可以匹配

^```

, lazy-repeat any character, until you get to another ,懒惰重复任何角色,直到你到达另一个角色

^```

. The ^ at the beginning ensures that the three backticks are at the beginning of a line, and the [\\s\\S] below is a way to match any character , including linebreaks, which . 开头的^确保三个反引号位于一行的开头,下面的[\\s\\S]是一种匹配任何字符的方法 ,包括换行符. does not do by default: 默认情况下不会这样做:

 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```"); 

This could be another way to replace the starting and ending triple back-tick "```" to <quote> and </quote> respectively. 这可能是另一种方法,分别将起始和结束三重反向勾选“``”替换为<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