简体   繁体   中英

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.

<!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

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 .

Try

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

because you are adding ,SPACE (two characters)

 <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); 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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