查找和替换分组主题标签的实例
Find and replace instances of grouped hashtags
我有一个像这样的降价字符串:
var str = "# This is a title ## This is a subtitle ###Paragraph title";
我想为每个标题添加一个标签,这样当降价呈现为 HTML 时,它们都呈现为下面的标题标签。我想实现以下字符串:
var str = "## This is a title ### This is a subtitle ####Paragraph title";
我试过用一个简单的替换来做到这一点:
str.replace("###", "####");
但现在当我执行上面的下一个标签时,它会匹配下面标签的实例,因为它还有 2 个主题标签:
str.replace("##", "###");
这不好,我想这需要用正则表达式来完成。是否可以按照我想要的方式匹配和替换它们,如何完成?
使用分组非常简单。
使用replace(/(#+)/g, "#")
Online Demo 正则表达式解释在左侧。
解释:
"search all one and more # and replace each matched group with one extra #"
var str = "# This is a title ## This is a subtitle ###Paragraph title".replace(/(#+)/g, "#");
document.write(str);
要用 n + 1 个哈希值替换 n 个哈希值字符串的每个实例,您可以使用 str.replace(/#+/g, '$&#')
我有一个像这样的降价字符串:
var str = "# This is a title ## This is a subtitle ###Paragraph title";
我想为每个标题添加一个标签,这样当降价呈现为 HTML 时,它们都呈现为下面的标题标签。我想实现以下字符串:
var str = "## This is a title ### This is a subtitle ####Paragraph title";
我试过用一个简单的替换来做到这一点:
str.replace("###", "####");
但现在当我执行上面的下一个标签时,它会匹配下面标签的实例,因为它还有 2 个主题标签:
str.replace("##", "###");
这不好,我想这需要用正则表达式来完成。是否可以按照我想要的方式匹配和替换它们,如何完成?
使用分组非常简单。
使用replace(/(#+)/g, "#")
Online Demo 正则表达式解释在左侧。
解释:
"search all one and more # and replace each matched group with one extra #"
var str = "# This is a title ## This is a subtitle ###Paragraph title".replace(/(#+)/g, "#");
document.write(str);
要用 n + 1 个哈希值替换 n 个哈希值字符串的每个实例,您可以使用 str.replace(/#+/g, '$&#')