我有一个包含巨大文本的对象,如下例所示。
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:5
和 5-6
之前有一个换行符,如下所示出色地。正则表达式将匹配这些内容并将其匹配的内容放入第 1 组中。然后,匹配项将替换为新行,后跟第 1 组中的内容。
关于javascript - 如何使用正则表达式在字符串中数字出现的开头添加\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54880498/