Is there a JavaScript function that can pad a string to get to a determined length?

前端 未结 30 1858
悲哀的现实
悲哀的现实 2020-11-22 08:28

I am in need of a JavaScript function which can take a value and pad it to a given length (I need spaces, but anything would do). I found this:

Code:

30条回答
  •  梦谈多话
    2020-11-22 09:09

    A variant of @Daniel LaFavers' answer.

    var mask = function (background, foreground) {
      bg = (new String(background));
      fg = (new String(foreground));
      bgl = bg.length;
      fgl = fg.length;
      bgs = bg.substring(0, Math.max(0, bgl - fgl));
      fgs = fg.substring(Math.max(0, fgl - bgl));
      return bgs + fgs;
    };
    

    For example:

    mask('00000', 11  );   // '00011'
    mask('00011','00' );   // '00000'
    mask( 2     , 3   );   // '3'
    mask('0'    ,'111');   // '1'
    mask('fork' ,'***');   // 'f***'
    mask('_____','dog');   // '__dog'
    

提交回复
热议问题