我在 javascript 中得到两个不同的字符串长度。一个来自输入字段,另一个来自直接 js 字符串值。例如,如果我将输入字段值设置为与 js 变量str2
i,e: 中的静态输入相同\u002Funits\u002F0004\u002F62a345b3-ead7-4d06-a65b-243fc54780ec
。我得到在控制台不同字符串长度(63和48),用于从变量相同的输入str
和str2
var checklen = function() {
var str = document.getElementById("text").value;
str = str.trim();
console.log(str);
console.log(str.length);
var str2 = "\u002Funits\u002F0004\u002F62a345b3-ead7-4d06-a65b-243fc54780ec";
console.log(str2.length);
}
Run Code Online (Sandbox Code Playgroud)
<div id='form'>
text <input type="text" name="text" id="text" />
<input type="button" onclick="checklen()" value="check">
</div>
Run Code Online (Sandbox Code Playgroud)
因为当你像这样直接将字符串放入 javascript 时
var str2 = "\u002Funits\u002F0004\u002F62a345b3-ead7-4d06-a65b-243fc54780ec";
Run Code Online (Sandbox Code Playgroud)
javascript 将解释\
为特殊字符转义因此结果将如所示colsole.log
但是如果你把两个\\
第一个取消第二个并且字符串会按预期运行
var str2 = "\u002Funits\u002F0004\u002F62a345b3-ead7-4d06-a65b-243fc54780ec";
Run Code Online (Sandbox Code Playgroud)
var checklen = function() {
var str = document.getElementById("text").value;
str = str.trim();
console.log(str);
console.log(str.length);
var str2 = "\u002Funits\u002F0004\u002F62a345b3-ead7-4d06-a65b-243fc54780ec";
console.log(str2.length);
console.log(str);
console.log(str2);
var str3 = "\\u002Funits\\u002F0004\\u002F62a345b3-ead7-4d06-a65b-243fc54780ec";
console.log("str len: ", str.length);
console.log("str2 len: ", str2.length);
console.log("str3 len: ", str3.length);
console.log("str: ", str);
console.log("str2: ", str2);
console.log("str3: ", str3);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
53 次 |
最近记录: |