Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 789
alexchenco Avatar asked Sep 08 '18 10:09

alexchenco


Video Answer


2 Answers

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```");
like image 137
CertainPerformance Avatar answered Oct 23 '22 22:10

CertainPerformance


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);
like image 38
Always Sunny Avatar answered Oct 23 '22 23:10

Always Sunny