我用字幕文件正则表达式粉碎了部分时间。我想将带有 Foreach 的 html 添加到所有返回值中。在值中,它将 html 添加到最新值。我希望他添加到所有值中。
示例 html:
<pre id="subtitle_txt">
1
00:00:00.05 -->; 00:00:03.02
Hello , Users.
2
00:00:03.02 -->; 00:00:05.00
Yep dude, it works successfully!
3
00:00:05.00 -->; 00:00:07.07
Have fun !
</pre>
jquery 片段:
$('#subtitle_txt').text(data);
const regex = /\d+:\d+:\d+.\d+ --> \d+:\d+:\d+.\d\d|[,\/]\d\d/g;
let m;
while ((m = regex.exec(data)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
m.forEach((match, groupIndex) => {
$('#subtitle_txt').html($('#subtitle_txt').text().replace(match, '<x style="color:red">' + match + '</x>'));
console.log(match);
});
}
结果:
我希望这里的所有时间标签都是红色的。
最佳答案
除了一些小事情(例如您的文本包含分号 -->;
因此它与任何内容都不匹配)之外,问题在于这一行:
$('#subtitle_txt').html($('#subtitle_txt').text().replace(
使用 .text()
读取现有值,该值会删除之前添加的任何 html 标签。
您可以将其更改为读一次/写一次,效果很好:
var data = $('#subtitle_txt').text();
const regex = /\d+:\d+:\d+.\d+ --> \d+:\d+:\d+.\d\d|[,\/]\d\d/g;
let m;
while ((m = regex.exec(data)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
m.forEach((match, groupIndex) => {
data = data.replace(match, '<x style="color:red">' + match + '</x>');
console.log(match);
});
$("#subtitle_txt").text(data);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre id="subtitle_txt">
1
00:00:00.05 --> 00:00:03.02
Hello , Users.
2
00:00:03.02 --> 00:00:05.00
Yep dude, it works successfully!
3
00:00:05.00 --> 00:00:07.07
Have fun !
</pre>
关于javascript - 使用 Regex 和 Jquery 替换页内 multi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58926536/