0

I am trying to remove the character from where the alphabets are occurs.

For example

var str1 = 1001;
// if there is no alphabates, then i want to print same as it is,
//so, output: 1001

var str2 = 1001R
var str3 = 1001R1

//Expecting output = 1001 for both str2 and str3

I tried this way

var selecteVendorID = $(".chequeTable .selected .tdVendorID").text(); //1001
alert('before : ' + selecteVendorID);  //before : 1001

selecteVendorID = selecteVendorID.slice(0, selecteVendorID.indexOf(selecteVendorID.match(/[a-zA-Z]/)));
alert(selecteVendorID);  //100

it is removing last number.

Note

if var str = '1001R'

that above code is working properly,

Community
  • 1
  • 1
Liam neesan
  • 2,282
  • 6
  • 33
  • 72
  • 1
    Try this link: https://stackoverflow.com/questions/4388055/remove-all-non-digit-characters-from-a-string-jquery – Kannan K Nov 08 '17 at 12:00

2 Answers2

0

javascript slice() method with negative arguments search from the backward direction.

In your case, when the regex doesn't match, it returns a -1, which evaluates to the function being string.slice(0, -1) which means, from the beginning to 1 from the last.

Change the code to :

firstAlphaIndex = selecteVendorID.indexOf(selecteVendorID.match(/[a-zA-Z]/));
selecteVendorID = selecteVendorID.slice(0, firstAlphaIndex>0?firstAlphaIndex:selecteVendorID.length);
alert(selecteVendorID);  //100
Vj-
  • 722
  • 6
  • 18
0

Try like this.

Var str = '100f1';
var position= str.indexOf(str.match(/[a-z A-Z]));
Var res= str.substring(0,position)+ str.substring(position+1, strict.length);
Kumar
  • 1
  • 1
  • 1