我有一串文本,其中可以包含特定的标签。
示例:var string = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';
我要做的是对 <pause #></pause>
进行正则表达式匹配标签。
对于找到的每个标签,在本例中为 <pause 4></pause>
和 <pause 7></pause>
.我要的是抢值4
和 7
, 以及 <pause #>...</pause>
之间的字符串的字符串长度除以标签。
我现在拥有的并不多。 但我不知道如何获取所有案例,然后遍历每个案例并获取我正在寻找的值。
我的功能目前看起来像这样,并不多:
/**
* checkTags(string)
* Just check for tags, and add them
* to the proper arrays for drawing later on
* @return string
*/
function checkTags(string) {
// Regular expresions we will use
var regex = {
pause: /<pause (.*?)>(.*?)<\/pause>/g
}
var matchedPauses = string.match(regex.pause);
// For each match
// Grab the pause seconds <pause SECONDS>
// Grab the length of the string divided by 2 "string.length/2" between the <pause></pause> tags
// Push the values to "pauses" [seconds, string.length/2]
// Remove the tags from the original string variable
return string;
}
如果有人能解释我如何做到这一点,我将非常感激! :)
最佳答案
match(/.../g)
不保存子组,您将需要 exec
或 replace
来做那。下面是一个基于 replace
的辅助函数的示例,用于获取所有匹配项:
function matchAll(re, str) {
var matches = [];
str.replace(re, function() {
matches.push([...arguments]);
});
return matches;
}
var string = '<pause 4>This is a line of text.</pause><pause 7>This is the next part of the text.</pause>';
var re = /<pause (\d+)>(.+?)<\/pause>/g;
console.log(matchAll(re, string))
既然你要删除标签,你也可以直接使用replace
。
关于Javascript 正则表达式匹配并从字符串中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44609258/