最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS Regex lookbehind not working in firefox and safari - Stack Overflow

programmeradmin0浏览0评论

I have this following regex which is working in chrome but causes an error in firefox or safari. I need to modify it to make it work. Can anybody help out a poor soul? Thanks in advance!

regex: /(?=<tag>)(.*?)(?<=<\/tag>)/

Basically, I have to match any char in between <tag> and </tag> and need to retain both tags. I used this expression as an argument to array.split.

input: "The quick brown <tag>fox</tag> jumps over the lazy <tag>dog</tag>"

operation: input.split(regex)

output: ["The quick brown ", "<tag>fox</tag>", " jumps over the lazy ", "<tag>dog</tag>"]

I have this following regex which is working in chrome but causes an error in firefox or safari. I need to modify it to make it work. Can anybody help out a poor soul? Thanks in advance!

regex: /(?=<tag>)(.*?)(?<=<\/tag>)/

Basically, I have to match any char in between <tag> and </tag> and need to retain both tags. I used this expression as an argument to array.split.

input: "The quick brown <tag>fox</tag> jumps over the lazy <tag>dog</tag>"

operation: input.split(regex)

output: ["The quick brown ", "<tag>fox</tag>", " jumps over the lazy ", "<tag>dog</tag>"]

Share Improve this question edited Oct 19, 2019 at 4:36 webedward asked Oct 19, 2019 at 4:24 webedwardwebedward 1031 gold badge1 silver badge5 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 12

Firefox and Has
Safari doesn't have support for lookbehind yet, you can use capture group ( used so that this the pattern on which we are splitting will be also be added in output ) and split on <tag> </tag>

let str = "The quick brown <tag>fox</tag> jumps over the lazy <tag>dog</tag>"

let regex = /(<tag>.*?<\/tag>)/

console.log(str.split(regex).filter(Boolean))

Maybe,

<tag>.*?<\/tag>|[^<>]+

would work OK:

Test

function regularExpression(regex, str) {
	let m, arr = [];
	while ((m = regex.exec(str)) !== null) {
		// This is necessary to avoid infinite loops with zero-width matches
		if (m.index === regex.lastIndex) {
			regex.lastIndex++;
		}


		m.forEach((match, groupIndex) => {
			arr.push(match.trim());
			console.log(`Found match, group ${groupIndex}: ${match}`);
		});
	}
	return arr;
}

const expression = /<tag>.*?<\/tag>|[^<>]+/g;
const string = 'The quick brown <tag>fox</tag> jumps over the lazy <tag>dog</tag>';

console.log(regularExpression(expression, string));


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

发布评论

评论列表(0)

  1. 暂无评论