对于小于 256 的值,将字符串中的所有字符转换为其十六进制格式
Converting all characters in a string to it's hexadecimal format for values less than 256
我需要将字符串中的所有字符显示为十六进制格式'\xHH'。下面是我一直在尝试的代码lately.I我只能将第一个字符串转换成十六进制格式format.But 不是全部。
for(i=0;i<inputString.length;i++){
if(inputString.charAt(i)<256){
inputString.replace(inputString .charAt(i),'\x'+inputString.charCodeAt(i).toString(16));
}
}
return inputString;
您的问题可能是在 if
条件下,因为您将 char 与 256
进行比较,而不是 char 代码,因此您可能需要:
if(inputString.charCodeAt(i)<256) // instead of inputString.charAt(i)<256
要获得更实用的方法,您可以使用此方法:
string
.split("")
.filter(c => c.charCodeAt(0) < 256)
.map(c => '\x' + c.charCodeAt(0).toString(16))
.join("")
let string = "something";
// filtering out the ones greater than 256
console.log(
string
.split("")
.filter(c => c.charCodeAt(0) < 256)
.map(c => '\x' + c.charCodeAt(0).toString(16))
.join("")
);
// not filtering out the ones greater than 256
console.log(
string
.split("")
.map(c => (c.charCodeAt(0) < 256 ? '\x' + c.charCodeAt(0).toString(16) : c))
.join("")
);
我需要将字符串中的所有字符显示为十六进制格式'\xHH'。下面是我一直在尝试的代码lately.I我只能将第一个字符串转换成十六进制格式format.But 不是全部。
for(i=0;i<inputString.length;i++){
if(inputString.charAt(i)<256){
inputString.replace(inputString .charAt(i),'\x'+inputString.charCodeAt(i).toString(16));
}
}
return inputString;
您的问题可能是在 if
条件下,因为您将 char 与 256
进行比较,而不是 char 代码,因此您可能需要:
if(inputString.charCodeAt(i)<256) // instead of inputString.charAt(i)<256
要获得更实用的方法,您可以使用此方法:
string
.split("")
.filter(c => c.charCodeAt(0) < 256)
.map(c => '\x' + c.charCodeAt(0).toString(16))
.join("")
let string = "something";
// filtering out the ones greater than 256
console.log(
string
.split("")
.filter(c => c.charCodeAt(0) < 256)
.map(c => '\x' + c.charCodeAt(0).toString(16))
.join("")
);
// not filtering out the ones greater than 256
console.log(
string
.split("")
.map(c => (c.charCodeAt(0) < 256 ? '\x' + c.charCodeAt(0).toString(16) : c))
.join("")
);