使用美元符号($)作为替换时,`string.replace`奇怪的行为 [英] `string.replace` weird behavior when using dollar sign ($) as replacement

查看:228
本文介绍了使用美元符号($)作为替换时,`string.replace`奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的JavaScript代码中发现了一个错误,我已经将其隔离到一个字符串替换中,这种错误的行为方式与我没想到的一样。以下是代码示例:

I found a bug in my JavaScript code that I have isolated to a string replace that is acting in a way I didn't expect. Here is an example of the code:

var text = "as";
text = text.replace(text,"$\'");
console.log(text);

这会向控制台输出一个空字符串。我原以为它要打印$'到控制台。有谁能解释一下?

This prints an empty string to the console. I was expecting it to print $' to the console. Can anyone explain this?

推荐答案

为了在结果字符串中使用 $ ,请使用 $$ as $ 在JavaScript正则表达式和字符串替换方法: https://developer.mozilla.org/en/ JavaScript / Reference / Global_Objects / String / replace#Specifying_a_string_as_a_parameter

In order to use $ in resulting string, use $$ as $ has special meaning in JavaScript Regular Expressions and String replace method: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter

这篇关于使用美元符号($)作为替换时,`string.replace`奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆