计算 Javascript 中具有特殊字符的字符串的长度

Count the length of a string with special chars in Javascript

所以,我有一个像这样的字符串

"v\xfb\"lgs\"kvjfywmut\x9cr"

我想在 Javascript 中找出它的大小。问题是,如果我将它复制到控制台,控制台将取消转义整个字符串。将其转换为:

"vû"lgs"kvjfywmutr"

我不希望这种情况发生。任何 tips/tricks?

如果你想要源字符的数量(包括转义字符),没有编程的方法来确定它,你必须通过查看源来完成代码和计数。

无法以编程方式做到这一点的原因是,一旦它是一个字符串,它就是一个字符串,并且可以使用转义序列以多种不同的方式编写相同的字符串。

例如,这些都定义了相同的字符串:

var s1 = "v\xfb\"lgs\"kvjfywmut\x9cr";
var s2 = 'v\xfb"lgs"kvjfywmut\x9cr';
var s3 = "\x76\xfb\"lgs\"k\x76jfywmut\x9cr";

...但如您所见,源字符的数量不同。

我知道这不是“正确”的答案,但我正在研究同样的问题并想出了一个解决方法。如果将字符串保存在文本文件中,使用fetch读取文件,可以统计出一个字符串的长度,包括转义字符和外引号。

假设您的字符串位于名为“strings.txt”的文件中:

fetch("strings.txt") // Connect to the URL Endpoint
        .then( // and then
          response => response.text() // take the response file
            .then( // and then...
              data => { // Do something with the data
                // if the file is only one line
                console.log(data.split('\n')[0].length); // 28 for your string

                // If the file has multiple lines                                   
                data.split('\n').forEach(v => console.log(v.length));
                    // 28, 27, 34 for T.J. Crowder's strings
                
              }
            )
        )