我有一个包含大量文本的对象,如下例所示。
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);
}
我的预期产出:
1这是样本文本。 2我想分开。 在一个数字的开头加上\n, 每当有数字出现时;在这个字符串中 例如,我可以有个地方 也是5-6。如何实现 使用javascript和 8 8regex
如何使用regex和javascript实现它。请帮帮我!
提前谢谢。最好的答案将不胜感激。
发布于 2019-02-26 07:48:43
您可以使用这个regex:
/(\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组。然后,匹配将被替换为一个新的行,后面跟着第一组中的任何内容。
发布于 2019-02-26 07:48:45
你可以用
/\s([0-9])/greplace所有在其前面有空格\s的数字都要用\n$1表示。
$1指捕获组([0-9])
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;
const result = quote.replace("\n", "\\n")
.replace(/\s([0-9])/g, '\n$1');
console.log(result);
}
发布于 2019-02-26 07:53:26
您可以使用“向前看”在数字前面插入一个换行符,后面跟着单词、字符、连字符或冒号,
quote.replace(/(?=\d+(?:[:-]|\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 result = quote.replace(/(?=\d+(?:[:-]|\w+))/g,'\n');
console.log('Result: ', result);
}
https://stackoverflow.com/questions/54880498
复制相似问题