将视频说明中的时间戳转换为链接

时间:2019-07-07 19:43:06

标签: javascript regex

我有一个页面,用户可以在其中添加视频说明。我希望能够在说明中标识时间戳,类似于YouTube的时间戳。据我所知,编写正则表达式是查找这些时间戳的最佳方法。目前,我的脚本无法正常工作。

function timestampify(text) {
    return text.replace(/\d+$/, '', '<a data-time="$1" class="timestamp-link">$1</a>')
}
/*
Music used:
0:00 - Rhythm Heaven - Rhythm Calligraphy
1:46 - Mario Party 6 - Night at the Garage
3:00 - POKEMON: Super Mystery Dungeon - Onward, Expedition Society!
36:10 - Mario Party 9 - DK's Jungle Ruins
47:23 - Rhythm Heaven - Rhythm Calligraphy
01:03:23 - Rhythm Heaven Fever: Prologues - Power Calligraphy Prologue
*/

2 个答案:

答案 0 :(得分:0)

为确保该值代表时间,我将使用以下内容:

/^[0-5]?\d(?::[0-5]?\d){1,2}/gm

Regex demo

故障:

^             # The beginning of the string/line.
[0-5]?        # And optional number between 0 and 5.
\d            # Any digit.
(?:           # The start of a non-capturing group.
    :         # Matches the character ":" literally.
    [0-5]?\d  # Any digit, optionally preceded by a number between 0 and 5.
)             # The end of the non-capturing group.
{1,2}         # Match between one and two times of the previous group (`ss` or `mm:ss`).

JavaScript示例:

function timestampify(text) {
    return text.replace(/^[0-5]?\d(?::[0-5]?\d){1,2}/gm, '<a data-time="$&" class="timestamp-link">$&</a>')
}

var text = `
0:00 - Rhythm Heaven - Rhythm Calligraphy
1:46 - Mario Party 6 - Night at the Garage
3:00 - POKEMON: Super Mystery Dungeon - Onward, Expedition Society!
36:10 - Mario Party 9 - DK's Jungle Ruins
47:23 - Rhythm Heaven - Rhythm Calligraphy
01:03:23 - Rhythm Heaven Fever: Prologues - Power Calligraphy Prologue
`

console.log(timestampify(text))

答案 1 :(得分:-1)

如果我们不验证时间戳,那么此表达式可能就可以工作:

\s*(\d{1,2}:\d{2}(?::\d{2})?)\s+

(在this demo右上角进行了说明,如果您想进一步探索或修改它,在this link中,您可以逐步观察它如何与某些示例输入匹配) ,如果您愿意。

const regex = /\s*(\d{1,2}:\d{2}(?::\d{2})?)\s+/gm;
const str = `0:00 - Rhythm Heaven - Rhythm Calligraphy
11:46 - Mario Party 6 - Night at the Garage
23:00 - POKEMON: Super Mystery Dungeon - Onward, Expedition Society!
  36:10 - Mario Party 9 - DK's Jungle Ruins
47:23 - Rhythm Heaven - Rhythm Calligraphy
01:03:23 - Rhythm Heaven Fever: Prologues - Power Calligraphy Prologue
   01:03:23 - Rhythm Heaven Fever: Prologues - Power Calligraphy Prologue`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}