Javascript 和反斜杠替换
这是我的字符串:
var str = "This is my \string";
这是我的代码:
var replaced = str.replace("/\\/", "\\\\");
我无法得到我的输出:
"This is my \\string"
我已经尝试了我能想到的正则表达式和替换值的每种组合。
任何帮助表示赞赏!
here is my string:
var str = "This is my \string";
This is my code:
var replaced = str.replace("/\\/", "\\\\");
I can't get my output to be:
"This is my \\string"
I have tried every combination I can think of for the regular expression and the replacement value.
Any help is appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
被这个问题困扰了很长时间,所有的答案都坚持认为源字符串需要已经转义了反斜杠......但情况并非总是如此。
这样做..
Got stumped by this for ages and all the answers kept insisting that the source string needs to already have escaped backslashes in it ... which isn't always the case.
Do this ..
该字符串不包含反斜杠,它包含
\s
转义序列。如果你想要一个正则表达式,你应该有一个正则表达式,而不是一个字符串。
The string doesn't contain a backslash, it contains the
\s
escape sequence.And if you want a regular expression, you should have a regular expression, not a string.
问题是第一行中的 \ 甚至无法识别。它认为反斜杠将标记转义序列,但 \s 不是转义字符,因此它被忽略。您的 var str 被解释为“这是我的字符串”。尝试
str.indexOf("\\")
- 你会发现它是 -1,因为根本没有反斜杠。如果您控制 str 的内容,请按照 David 所说的操作 - 添加另一个 \ 来转义第一个。The problem is that the \ in your first line isn't even recognized. It thinks the backslash is going to mark an escape sequence, but \s isn't an escape character, so it's ignored. Your var str is interpreted as just "This is my string". Try
str.indexOf("\\")
- you'll find it's -1, since there is no backslash at all. If you control the content of str, do what David says - add another \ to escape the first.结果:
Result:
如果您有多个实例或反斜杠:
In case you have multiple instances or the backslash:
使用这个
或
“某事”它可能是字符串中不存在的字符的组合
Use this
or
'something' it may be a combination of characters that is not in string
我认为混乱来自于字符串在浏览器控制台中的显示方式。 (我刚刚检查了 chrome)
这里 myString 实际上不包含任何反斜杠字符。它包括解析为
s
的\s
序列。所以如果你在控制台中显示你的字符串:
下面的字符串虽然只有 1 个反斜杠:
所以最后如果你想用 2 个反斜杠替换反斜杠字符,你可以这样做:
I think the confusion is coming from how a string is displayed in the browser console. (I just checked chrome)
Here myString is actually doesn't include any backslash char. It includes
\s
sequence which resolves tos
.So If you display your string in the console:
The following string though has only 1 backslash in it:
So finally if you want to replace backslash char with 2 backslashes you can do this:
如果用例是替换函数的 toString 中的某些值,并将字符串转换回有效的函数。
If use case is to replace some values in the toString of a function, and convert the string back to a valid function.
我还没有尝试过这个,但是下面的应该可以工作
本质上你不想替换“\”,你想替换由“\s”转义序列表示的字符。
不幸的是,您需要对字母表中的每个字母、每个数字、符号等执行此操作,才能覆盖所有基础
I haven't tried this, but the following should work
Essentially you don't want to replace "\", you want to replace the character represented by the "\s" escape sequence.
Unfortunately you're going to need to do this for every letter of the alphabet, every number, symbol, etc in order to cover all bases