Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the string length is different for the same string in input field and as static value of variable string in JS

Tags:

javascript

I am getting two different string length in javascript. One from the input field and the other from the direct js string value. For example if I set the input field value as same as the static input in js variable str2 i,e: \u002Funits\u002F0004\u002F62a345b3-ead7-4d06-a65b-243fc54780ec. I get different string length (63 and 48)in the console for the same input from variable str and 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);

}
<div id='form'>
  text <input type="text" name="text" id="text" />

  <input type="button" onclick="checklen()" value="check">
</div>
like image 667
alamin_cse07 Avatar asked Oct 25 '25 16:10

alamin_cse07


1 Answers

because when you directly put the string into javascript like this

  var str2 = "\u002Funits\u002F0004\u002F62a345b3-ead7-4d06-a65b-243fc54780ec";

javascript will interpret \ as special character escape hence the result will be as shown in colsole.log however if you put two \\ the first one cancel the second one and the string would behave as expected

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);
}
<div id='form'>
  text <input type="text" name="text" id="text" />

  <input type="button" onclick="checklen()" value="check">
</div>
like image 89
Andam Avatar answered Oct 27 '25 05:10

Andam