LoginSignup
12
12

More than 3 years have passed since last update.

【javascript】数値文字列の先頭の0を削除(ゼロサプレス)

Last updated at Posted at 2020-10-25

前書き

ゼロパディングの逆がしたくなりました。
以下のように変換。

'000001230' => '1230'

(追記)

投稿後に検索したら以下でもできると知りました。

Number('000001230');    //1230

状況が合えばこのパターンも良いですね。

コード(3パターン)

正規表現

const suppressZero1 = str => {
    //略
    return str.replace(/^0+/, '');
};
console.log( suppressZero1('000001230') );  //'1230'

配列化

const suppressZero2 = str => {
    //略
    const idx = str.split('').findIndex(x => x!=='0');
    return str.slice(idx);
};
console.log( suppressZero2('000001230') );  //'1230'

while

const suppressZero3 = str => {
    //略
    let idx = 0;
    while (str.charAt(idx)==='0') idx++;
    return str.slice(idx);
};
console.log( suppressZero3('000001230') );  //'1230'

速度

私の環境での処理時間は
(速<遅)while =< 配列化 << 正規表現
の順番でした。

(コード追記)マイナスと小数点以下も処理

コメントでマイナス考慮しないの?って言われたのでwhileベースで書きました。
やっつけなので問題あれば教えてください。

const suppressZero3 = str => {
    //事前検査
    if (typeof str !== 'string') return;
    if (!/^-?\d+(\.\d+)?$/.test(str)) return;

    //先頭の切り出し位置の特定
    let start = 0;
    const minus = str.startsWith('-') ? (start++, '-') : '';
    while (str.charAt(start)==='0') start++;

    if (!str.includes('.')) return minus + str.slice(start);

    //後方の切り出し位置の特定
    let end = str.length - 1;
    while (str.charAt(end)==='0') end--;

    return minus + str.slice(start, end + 1);
};
console.log( suppressZero3('-000001230.0045678900000') );   //'-1230.00456789'

ここまでやると正規表現を使った置換で良さそうな気がします。

12
12
8

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12