-4
function() {
    var address =  $("#postcode").val();
    var postcode = address.split(' ');
    postcode = "Postcode:"+postcode[(postcode.length-2)];
    return postcode;
}

This js pulls a postcode value from an online form when the user runs a query. I need to know how I get it to deliver the postcode less the last 2 characters. for example, SP10 2RB needs to return SP102.

  • 1
    Please try to do your own research before posting a question. A quick search of "JS get part of string" will give you plenty of answers. – Travesty3 Feb 17 '16 at 15:50

3 Answers3

1

Use substring() or substr() or slice().

Travesty3
  • 14,351
  • 6
  • 61
  • 98
1

You have to slice the string and return what you want:

return postcode.slice(0, -2);

// example
postcode = "sample";

// output
"samp"
0

You can use this function:

function postCode(address)
{
    var tmpAddr = address.replace(' ','');
  tmpAddr = tmpAddr.substr(0, tmpAddr.length-2);
  return tmpAddr;
}

alert(postCode('SP10 2RB'));
S. Nadezhnyy
  • 582
  • 2
  • 6