Javascript 正则表达式匹配并从字符串中获取值

标签 javascript regex

我有一串文本,其中可以包含特定的标签。 示例: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> .我要的是抢值47 , 以及 <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) 不保存子组,您将需要 execreplace 来做那。下面是一个基于 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/

相关文章:

Python 正则表达式 : Difference between (. +) 和 (.+?)

java - 用于处理字符或行尾的正则表达式匹配器

javascript - 上一首歌曲播放完毕后自动播放下一首

javascript - 如何处理空变量的默认值?

JavaScript API - 为什么只显示一对 JSON 键/值?

javascript - 使用 jQuery 设置和获取 localStorage

javascript - 如何用span标签替换特定的文本换行字符?

javascript - 自调用函数的括号符号是否在 Javascript 中有用?

php - 从文本文件中切片

jquery - 从 Jquery 字符串中删除第一个数字