简体   繁体   English

使用ASCII码在JavaScript中转义字符

[英]Escaping characters in JavaScript using their ASCII codes

I am creating a bookmarklet and I have to avoid using double quotes ( " ) because I have to include the bookmarklet inside a HTML page and it's inside a string that uses double quotes: 我正在创建一个书签,并且必须避免使用双引号(“),因为我必须在HTML页面中包括书签并将其包含在使用双引号的字符串中:

<a href="javascript:...">

In some places I have to use the code replace(/".*/, ''); 在某些地方,我必须使用代码replace(/".*/, '');

In sed, I can escape double quotes using \\x22 (22 is the ASCII hex code for double quotes) 在sed中,我可以使用\\x22转义双引号(22是双引号的ASCII十六进制代码)

Is it possible to do something similar in JavaScript like replace(/\\x22.*/, ''); 是否可以在JavaScript中做类似的事情,例如replace(/\\x22.*/, ''); ?

You can use the other syntax for making a RegExp and use String.fromCharCode 您可以使用其他语法制作RegExp并使用String.fromCharCode

Here's an example: 这是一个例子:

'"hello"'.replace(new RegExp(String.fromCharCode(34), 'g'), '-quotes-')

-->

'-quotes-hello-quotes-'

The same way you would use quotes in any HTML attribute's value. 与在任何HTML属性值中使用引号的方式相同。

example

<img src="..." alt="A picture of Bob &quote;Wild Man&quot; Johnson">

so for you 所以对你来说

<a href="javascript:replace(/&quot;.*/, '');">

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

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