簡體   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