我正在尝试使用正则表达式来定位时间并向其添加文本。但是当输入字符串有换行符时,我的正则表达式有问题。如果我删除了中断并测试表达式,它就可以工作。
此外,在找到目标时间后,如何在其前后添加文字?
var str = "00:00:01.120
In this lesson, we will learn how to determine the equation of a line, using the available information.
00:00:08.040
Let's look at the first example. Determine the equation of the line, that passes through the points (2, 5), and with the slope of 2.
00:00:19.000
To begin, we should know that the equation of a line can be written in the form of y = mx + b, where m is the slope, and b is the y-intercept.";
var patt1 = /(\d\d.\d\d.\d\d.\d\d\d)/gm;
var result = str.match(patt1);
答案 0 :(得分:0)
正如其他人所说,您需要先修复多行字符串。
完成此操作后,您可以使用replace
方法而不是match
方法在匹配时间之前和之后添加文字:
var str = "00:00:01.120\n\
In this lesson, we will learn how to determine the equation of a line, using the available information.\n\
\n\
00:00:08.040\n\
Let's look at the first example. Determine the equation of the line, that passes through the points (2, 5), and\ with the slope of 2.\n\
\n\
00:00:19.000\n\
To begin, we should know that the equation of a line can be written in the form of y = mx + b, where m is the\ slope, and b is the y-intercept.";
var patt1 = /(\d\d.\d\d.\d\d.\d\d\d)/gm;
//var result = str.match(patt1);
var result = str.replace(patt1, "<some text>\$1<some other text>");
alert(result);
您可以在fiddle中尝试此操作。
有关replace
方法的详细信息,请查看MDN's reference page。
答案 1 :(得分:0)
为str分配值的方式不正确。您的浏览器必须已阻止您的脚本,因此从未进行过解析。
您可以使用\ r \ n替换换行符,如下所示,
var str = "00:00:01.120\r\nIn this lesson, we will learn how to determine the equation of a line, using the available information.\r\n00:00:08.040\r\nLet's look at the first example. Determine the equation of the line, that passes through the points (2, 5), and with the slope of 2.\r\n00:00:19.000\r\nTo begin, we should know that the equation of a line can be written in the form of y = mx + b, where m is the slope, and b is the y-intercept.";
您可以查看此fiddle以查看其工作原理。