Red Cricket
Red Cricket

Reputation: 10460

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.

Upvotes: 0

Views: 99

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50664

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

Upvotes: 2

User863
User863

Reputation: 20039

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>

Upvotes: 2

Related Questions