开发者

How to write correct regex so JSLint will validate?

I use a very simple regex in a replace function that causes JSLint.com to report errors:

开发者_如何学运维
srcTemplate.replace(/{x}/g, tileX);

A quick search around the internet gave a lot of suggestions, but none of them answered my question:

How can I enhance the regex so JSLint will validate AND the function will keep working?


The regex /{x}/ is invalid because curly braces have special meaning in regular expressions. Some regex engines may still treat it as a valid regex by assuming that you probably meant literal curly braces instead of quantifiers, but perhaps JSLint is more strict here. So if you're planning to match a literal {x}, you need the regex

/\{x\}/

to be on the safe side (although it's unclear why you'd need a regex for that at all since it's a simple text replacement).

Usually, you use curly braces as a quantifier. For example x{3} matches xxx; x{3,5} matches xxx, xxxx and xxxxx, and so on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜