Remove zeroes from a alphanumeric string

redth
Giga Expert

Hi, I have a requirement to remove zeroes from an alphanumeric string. For example, pq010, pq003 should be displayed as pq10 and pq3. Only zeroes between the alphabets and number(1-9) should be removed. Can anyone please help with the code?

1 ACCEPTED SOLUTION

Jan Cernocky
Tera Guru

Try this, I am getting the ASCII value of small letters and ASII value of numbers (except for zero). If your string has also capital lters you need to adjust the condition.

Seems to be working pretty good, if the string is consistent (letters grouped from beginning)

var test = 'pq00000008765300001';
var test2 = '';
var lastCharacter = 0;
var firstDigit = 0;

for (i=0; i< test.length;i++) {
    var asciiCode = test.charCodeAt(i);
    if (asciiCode >= 97 && asciiCode <= 122) {
        lastCharacter = i;
    }
    if (asciiCode >= 49 && asciiCode <= 57) {
        firstDigit = i;
        break;
    }
}

if (lastCharacter > 0 && firstDigit > 0) {
    test2 = test.substring(0,lastCharacter+1) + test.substring(firstDigit,test.length);
}
else {
    test2 = test;
}

gs.info(test2);

View solution in original post

4 REPLIES 4

Jaspal Singh
Mega Patron
Mega Patron

You can try below i nbackground script once

var remove0='pq001000';
gs.print(remove0.replace('0','')); //Removes 1 zero
gs.print(remove0.replaceAll('0',''));// Removes all zeros

 

Hi Jaspal,

From the string pq001000, it should remove zeroes between q and 1. The final result should be pq1000. But the above script either removes one or all.

Jan Cernocky
Tera Guru

Try this, I am getting the ASCII value of small letters and ASII value of numbers (except for zero). If your string has also capital lters you need to adjust the condition.

Seems to be working pretty good, if the string is consistent (letters grouped from beginning)

var test = 'pq00000008765300001';
var test2 = '';
var lastCharacter = 0;
var firstDigit = 0;

for (i=0; i< test.length;i++) {
    var asciiCode = test.charCodeAt(i);
    if (asciiCode >= 97 && asciiCode <= 122) {
        lastCharacter = i;
    }
    if (asciiCode >= 49 && asciiCode <= 57) {
        firstDigit = i;
        break;
    }
}

if (lastCharacter > 0 && firstDigit > 0) {
    test2 = test.substring(0,lastCharacter+1) + test.substring(firstDigit,test.length);
}
else {
    test2 = test;
}

gs.info(test2);

Hitoshi Ozawa
Giga Sage
Giga Sage

Hi Akred,

function removeZeros(s) {
  var pattern1 = /^([a-z]|[1-9])+/g;
  var pattern2 = /^0*/;

  var arr = pattern1.exec(s);
  var pre = arr[0];
  s = s.replace(pre,'');

  arr = pattern2.exec(s);
  var suf = s.substring(arr[0].length);

  return  pre + suf;
}

Execution results:

case 1:

var s = 'pq010';
s = removeZeros(s);
gs.info(s);
*** Script: pq10

case 2:

var s = 'pq003';
s = removeZeros(s);
gs.info(s);
*** Script: pq3