title = title.replace(regex, ‘$1’);
$1 是什么意思
在正则表达式替换中,$1 是一个捕获组的占位符,表示第一个捕获的子表达式。捕获组是在正则表达式中用圆括号 () 括起来的部分。换句话说,$1 会被替换成匹配正则表达式中的第一个捕获组的内容。
title.replace(regex, ‘$1’) 使用正则表达式 regex 替换匹配的内容。
‘$1’ 表示将匹配的内容替换成带有红色样式的 span 标签,其中 $1 代表第一个捕获组的内容。
示例
假设 year_name 为 “2020年”,那么生成的正则表达式为 /(2020年)/g。当 title 包含 “2020年” 时,正则表达式匹配到 “2020年”,并将其替换为 2020年。
去掉字符串中的多余空格:
let str = " Hello, world! ";
let regex = /^\s*(.*?)\s*$/; // 捕获组包含有效内容
str = str.replace(regex, '$1');
console.log(str); // 输出: "Hello, world!"
替换日期格式
假设你有一个日期字符串 “2024-10-24”,你想将其格式化为 “10/24/2024”。
let date = "2024-10-24";
let regex = /(\d{4})-(\d{2})-(\d{2})/; // 捕获年、月、日
date = date.replace(regex, '$2/$3/$1');
console.log(date); // 输出: "10/24/2024"
移除 HTML 标签
假设你有一个包含 HTML 的字符串,想去掉标签
let htmlStr = "<div>Hello <b>world</b>!</div>";
let regex = /<[^>]+>(.*?)<\/[^>]+>/g; // 捕获组包含文本
htmlStr = htmlStr.replace(regex, '$1');
console.log(htmlStr); // 输出: "Hello world!"