简体   繁体   English

字符串替换 function 行为 - 错误“无需重复”

[英]String replace function behavior - error “nothing to repeat”

The below code gives the error:下面的代码给出了错误:

var a = "hello {0} world";
a.replace(/{0}/g, "little");

But this one works:但这一个有效:

var a = "hello {str} world";
a.replace(/{str}/g, "little");

Why do we get this error?为什么我们会收到这个错误?

Because {n} (with n being a positive integer) is quantifier syntax, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Quantifiers因为{n}n为正整数)是量词语法,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Quantifiers

You don't want the curly braces to have their “special meaning” here, but want them treated as plain characters - so you should escape them.您不希望花括号在此处具有其“特殊含义”,而是希望将它们视为普通字符 - 因此您应该将它们转义。

a.replace(/\{0\}/g,"little")

Problem问题

The number inside a curly brace has a special meaning, it is quanitifier syntax.花括号内的数字有一个特殊的含义,它是限定符语法。

Solution解决方案

You have to escape the curly braces with \{ \}你必须用\{ \}转义花括号

Here is an example这是一个例子

 var b = "hello {0} world"; console.log(b.replace(/\{0\}/g,"little"));

Your argument to replace() is a regular expression.你对replace()的参数是一个正则表达式。

In particular, braces { and } are regular expression metacharacters (they are a range quantifier ).特别是,大括号{}是正则表达式元字符(它们是范围量词)。

You must escape (with \ ) the braces in your regular expression for this to work.您必须转义(使用\ )正则表达式中的大括号才能使其正常工作。

For example, this:例如,这个:

a.replace(/\{0\}/g, "little");

would work.会工作。 This would treat the braces literally.这将按字面意思对待大括号。

The specific error message you get:您收到的具体错误消息:

SyntaxError: Invalid regular expression: /{0}/: Nothing to repeat SyntaxError:无效的正则表达式:/{0}/:无需重复

is because the engine expects some text to precede the quantifier, so for example, x{0} would be a valid argument as a regular expression.是因为引擎希望在量词之前有一些文本,因此例如, x{0}作为正则表达式将是一个有效的参数。

In the other case, using在另一种情况下,使用

a.replace(/{str}/g, "little");

does work, since the braces lose their special meaning as metacharacters, and get treated literally.确实有效,因为大括号失去了作为元字符的特殊含义,并按字面意思对待。 Range quantifiers must take the form {n} , {n,} or {n,m} where n and m are integers.范围量词必须采用{n}{n,}{n,m}的形式,其中nm是整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM