I am generating the following string with JavaScript:
"ISCP\x00\x00\x00\x10\x00\x00\x00\x09\x01\x00\x00\x00\x00\!1PWR01\x0D\x0A"
It represents a chain of text and Hex values.
In fact the actual underlying string is built up like this:
"ISCP\\x00\\x00\\x00\\x10\\x00\\x00\\x00\\x09\\x01\\x00\\x00\\x00\\x00\\!1PWR01\\x0D\\x0A"
As I have to escape the slashes to be able to work with them in the first place.
Now I have to somehow transform this string into a into a string of chained Hex values so that I can send it across a TCP connection. The result would look something like this:
\x49\x53\x43\x50\0\0\0\x10\0\0\0\t\x01\0\0\0\0\x21\x31\x50\x57\x52\x30\x31\r\n
But I don't know how to go about this.
You can use a regex to find all the \\xHH
-style sequences in your string and replace them with actual values. Since you cannot dynmically create literal \\xHH
escape sequences, you'll need to use a replacer callback with String.fromCharCode
:
var newString = myString.replace(/\\x([0-9A-F][0-9A-F])/g, function(m, g1) {
return String.fromCharCode(parseInt(g1, 16));
});
This parses the two digits following each \\x
as a base-16 value, and then uses that number as a character code to create a new one-character string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.