简体   繁体   中英

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 . 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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