简体   繁体   English

如果字符串javascript的最后一个字符如何摆脱?

[英]How do I get rid if the last character of a string javascript?

I do not understand why I cannot remove the last character in my string. 我不明白为什么我不能删除字符串中的最后一个字符。 Here is my javascript code. 这是我的JavaScript代码。

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
function array2ArrayOfStrings(arr) {
  var lines = [new Array()];
  var l = 0;
  lines[0].push(arr[0] + ', ');

  for(i=1; i < arr.length; i++) {
    lines[l] += arr[i] + ', ';
    if(lines[l].length > 20) {
      lines.push(new Array());
      l++;
    }
  }
  console.log('last is ' + lines[l]);
  // var newStr = str.substring(0, str.length - 1);
  lines[l] = lines[l].substring(0, lines[l].length - 1);
  // lines[l] = lines[l].slice(0,-1);
  return lines.join('<br>');
}

var cars = [
   'CRX',
   'Mustang',
   'Volvo XXX',
   'Toyota Pickup',
   'Volkswagon Beatle',
   'Datsun',
   'Lincoln',
   'Cadillac',
   'Mercedes',
   'Lexus',
];

document.getElementById("demo").innerHTML = array2ArrayOfStrings(cars);
</script>

</body>
</html>

Here's a link where you can run the above: https://www.w3schools.com/code/tryit.asp?filename=G6MDZQFMAK4K 这是您可以运行以上命令的链接: https : //www.w3schools.com/code/tryit.asp?filename=G6MDZQFMAK4K

The output I get is this: 我得到的输出是这样的:

CRX, Mustang, Volvo XXX, 
Toyota Pickup, Volkswagon Beatle, 
Datsun, Lincoln, Cadillac, 
Mercedes, Lexus,

I want to get rid of that last , after Lexus . 我想摆脱过去的,之后Lexus

Try 尝试

lines[l].substring(0, lines[l].length - 2);

because you are adding ,SPACE (two characters) 因为您要添加,SPACE (两个字符)

 <p id="demo"></p> <script> function array2ArrayOfStrings(arr) { var lines = [new Array()]; var l = 0; lines[0].push(arr[0] + ', '); for (i = 1; i < arr.length; i++) { lines[l] += arr[i] + ', '; if (lines[l].length > 20) { lines.push(new Array()); l++; } } lines[l] = lines[l].substring(0, lines[l].length - 2); console.log('last is ' + lines[l]); return lines.join('<br>'); } var cars = [ 'CRX', 'Mustang', 'Volvo XXX', 'Toyota Pickup', 'Volkswagon Beatle', 'Datsun', 'Lincoln', 'Cadillac', 'Mercedes', 'Lexus', ]; document.getElementById("demo").innerHTML = array2ArrayOfStrings(cars); </script> 

Your code actually is removing the last character in your string. 您的代码实际上是删除字符串中的最后一个字符。 At the moment the last character is a space as you are appending , to your last element, so, when you do lines[l] = lines[l].substring(0, lines[l].length - 1); 目前的最后一个字符是因为你是一个附加的空间,你的最后一个元素,所以,当你做lines[l] = lines[l].substring(0, lines[l].length - 1); you're removing the space, and not the the comma , . 您要移除的空间,而不是逗号, To remove both the space and comma, you need to change your -1 to a -2 like so: 要同时删除空格和逗号,您需要将-1更改为-2如下所示:

lines[l] = lines[l].substring(0, lines[l].length - 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM