gpt4 book ai didi

javascript String.length 返回错误的字符数

转载 作者:太空宇宙 更新时间:2023-11-04 03:27:56 24 4
gpt4 key购买 nike

我今天遇到了一个奇怪的 JavaScript 行为,这可能是由于某些字符编码问题造成的。 length 函数为明显相同的字符串返回两个不同的字符数。在一种情况下,字符串是从数据库值复制粘贴的,在第二种情况下,我用键盘手动写入字符。我确信这与 UTF 相关,但我不知道如何获得“正确”的字符数。有没有办法知道有问题的字符串采用哪种编码并以某种方式“修复”它?有没有办法强制我的应用程序中的每个字符串都为 UTF-8 ?某处是否有隐藏 Angular 色?

感谢您的帮助

var utils = {

/**
* cleans up our url before db insertion
*
* @param url
* @returns {String} the cleaned url
*/
cleanUrl : function(url){
url = url.trim().toLowerCase();
if(url.includes('?'))return url;

var lastChar = url.charAt(url.length-1);
console.log('lastchar = ' + lastChar);
if(lastChar == '/'){
url=url.substring(0, url.length-1);
}
return url;
},

doTest : function(){
var url = "https://bitcointalk.org/‎"; //this string was taken from DB
console.log('url length ' + url.length);
console.log('url length ' + url.trim().length);
var cleaned = this.cleanUrl(url);
console.log('cleaned length ' + cleaned.length);
console.log('cleaned ' + cleaned);


console.log('------------------------------');

var url2 = "https://bitcointalk.org/"; //this string was manually written
console.log('url2 length ' + url2.length);
console.log('url2 length ' + url2.trim().length);

var cleaned2 = this.cleanUrl(url2);
console.log('cleaned2 length ' + cleaned2.length);
console.log('cleaned2 ' + cleaned2);

}
};

utils.doTest()

这是输出:

url length 25
url length 25
lastchar = ‎
cleaned length 25
cleaned https://bitcointalk.org/‎
------------------------------
url2 length 24
url2 length 24
lastchar = /
cleaned2 length 23
cleaned2 https://bitcointalk.org

最佳答案

你说得对!如果您将两个字符串复制出来并在浏览器控制台中尝试,您可以看到数据库中编码的 secret 字符。

关于javascript String.length 返回错误的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42142178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com