javascript - 如何使用正则表达式在字符串中数字出现的开头添加\n

标签 javascript regex split

我有一个包含巨大文本的对象,如下例所示。

var obj ={ "text" : "1This is the sample text. 2that I want to split. 3And add \n in the beginning of a number, 4whenever there is a number occurrence; in this string 4:1 for example i can have somewhere 5-6 also. How to achieve it 7Using javascript and 8regex"

我需要添加 \n <br> 在数字出现之前。

我尝试过 /([0-9])\w+/g并加入 \n如下:

请运行代码片段以查看我的结果

var obj ={ "text" : "1This is the sample text. 2that I want to split. 3And add \n in the beginning of a number, 4whenever there is a number occurrence; in this string 4:1 for example i can have somewhere 5-6 also. How to achieve it 7Using javascript and 8regex"}

if(obj.text) {
    let quote = obj.text;
    var regex = /([0-9])\w+/g;
    var result = quote.split(regex).join('\n');
    console.log('result', result);
} 

我的预期输出:

1This is the sample text.

2that I want to split.

3And add \n in the beginning of a number,

4whenever there is a number occurrence; in this string

4:1 for example i can have somewhere

5-6 also. How to achieve it

7Using javascript and

8regex

如何使用正则表达式和 JavaScript 来实现它。请帮帮我!

提前致谢。最佳答案将不胜感激。

最佳答案

你可以使用这个正则表达式:

/(\d(?:[-:]\d)?)/g

并将其替换为

\n$1

代码:

var regex = /(\d(?:[-:]\d)?)/g;
var str = '1This is the sample text. 2that I want to split. 3And add \\n in the beginning of a number, 4whenever there is a number occurrence; in this string 4:1 for example i can have somewhere 5-6 also. How to achieve it 7Using javascript and 8regex';
var subst = '\n$1';

var result = str.replace(regex, subst);

console.log('result: ', result);

正则表达式将匹配所有数字和一些非数字,因为显然您希望在 4:55-6 之前有一个换行符,如下所示出色地。正则表达式将匹配这些内容并将其匹配的内容放入第 1 组中。然后,匹配项将替换为新行,后跟第 1 组中的内容。

关于javascript - 如何使用正则表达式在字符串中数字出现的开头添加\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54880498/

相关文章:

javascript - 带限制的拆分字符串,其中最后一个字符串包含余数

javascript - 如何处理 meteor 调用内或调用后的事件?

regex - 合并以 "+"开头的连续行

javascript - 无法根据正则表达式拆分字符串

javascript - 用 ; 分割字符串只要它不在之间 » «

Java split 函数给了我一小段结果字符串数组

javascript - 谷歌图表 : Error: Row 0 has 1 columns, 但必须有 2

javascript - 递归调用导致调用堆栈溢出但事件队列不会溢出?

javascript - 模糊对话框窗口的背景

php - MongoDB/PHP 库 : $regex does not work