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

前端 未结 30 1622
悲哀的现实
悲哀的现实 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 08:58

    I think its better to avoid recursion because its costly.

    function padLeft(str,size,padwith) {
    	if(size <= str.length) {
            // not padding is required.
    		return str;
    	} else {
            // 1- take array of size equal to number of padding char + 1. suppose if string is 55 and we want 00055 it means we have 3 padding char so array size should be 3 + 1 (+1 will explain below)
            // 2- now join this array with provided padding char (padwith) or default one ('0'). so it will produce '000'
            // 3- now append '000' with orginal string (str = 55), will produce 00055
    
            // why +1 in size of array? 
            // it is a trick, that we are joining an array of empty element with '0' (in our case)
            // if we want to join items with '0' then we should have at least 2 items in the array to get joined (array with single item doesn't need to get joined).
            // 000 to get 3 zero we need 4 (3+1) items in array   
    		return Array(size-str.length+1).join(padwith||'0')+str
    	}
    }
    
    alert(padLeft("59",5) + "\n" +
         padLeft("659",5) + "\n" +
         padLeft("5919",5) + "\n" +
         padLeft("59879",5) + "\n" +
         padLeft("5437899",5));

提交回复
热议问题