0

I would like to ask if it is possible to trim the length of multiple strings in an array in javascript. The length of each string of my array is different, however I would like to trim the last 2 digit (meaning trimming "-2") for each of them.

var array = ["517577144-2","503222534-2","100003527692828-2","654703438-2","4205501-2"]

Cheers, Karen

0

7 Answers 7

1

map function:

array = array.map(function(d){return d.substr(0,d.length-2)});

or you can use slice method inside:

array = array.map(function(d){return d.slice(0,-2)});
Sign up to request clarification or add additional context in comments.

1 Comment

@Moogs Good idea, updated the answer, string can be treated as an array:)
1

another option is you can use map along with slice function :

array = array.map(function(str){return str.slice(0,str.length-2)});

Comments

0

Look at the 'map' function. This should do it for you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Comments

0

You can try like this:

var x;
for(x = 0; x < 10; x++)
{
    array[x] = array[x].replace('-2', '');
}

JSFIDDLE DEMO

1 Comment

This, however, assumes that the '-2' substring only occurs at the ends of these strings.
0

This will remove the last character -2 in the array.

   array = array.map(function(item) {
      return item.replace('-2', '');
    })

If you want to remove any character which is at the last not specifically -2 then

 array = array.map(function(item) {
      return item.substr(0, item.length-2);
    })

Comments

0

Multiple ways to trim last two characters: substr, substring, replace or slice (cleanest solution).

var array = ["517577144-2","503222534-2","100003527692828-2","654703438-2","4205501-2"];

// Using substr method

var trimmed = array.map(function(item) {
  return item.substr(0,item.length - 2);
});

log(trimmed);


// Using substring method

trimmed = array.map(function(item) {
  return item.substring(0,item.length - 2);
});

log(trimmed);


// Using regular expression in replace method

trimmed = array.map(function(item) {
  return item.replace(/.{2}$/,'');
});

log(trimmed);


// Using slice method

trimmed = array.map(function(item) {
  return item.slice(0,-2);
});

log(trimmed);


function log(array) {
   document.write('<pre>' + JSON.stringify(array, null, 2) + '</pre>');
}

Instead of map you can always use a standard for loop too.

Comments

0

Using open source project jinqJs it would simply be

var result = jinqJs().from(array).select(function(row){return row.slice(0, row.length-2);});

See Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.