programing tip

javascript / jquery로 선행 0 제거 / 자르기

itbloger 2020. 11. 16. 07:55
반응형

javascript / jquery로 선행 0 제거 / 자르기


javascript, jquery로 숫자 (모든 문자열)에서 선행 0을 제거하거나 자르는 솔루션을 제안합니다.


문자열 시작 부분에서 0과 일치하는 정규식을 사용할 수 있습니다.

s = s.replace(/^0+/, '');

Number () 함수를 사용합니다.

var str = "00001";
str = Number(str).toString();
>> "1"

또는 문자열에 1을 곱합니다.

var str = "00000000002346301625363";
str = (str * 1).toString();
>> "2346301625363"

조금 늦었을 수도 있지만 2 센트를 더하고 싶습니다.

문자열이 항상 앞에 0이있는 숫자를 나타내는 경우 '+'연산자를 사용하여 문자열을 숫자로 간단히 캐스트 할 수 있습니다.

예 :

x= "00005";
alert(typeof x); //"string"
alert(x);// "00005"

x = +x ; //or x= +"00005"; //do NOT confuse with x+=x, which will only concatenate the value
alert(typeof x); //number , voila!
alert(x); // 5 (as number)

문자열이 숫자를 나타내지 않고 0 만 제거하면 다른 솔루션을 사용하지만 숫자로만 필요한 경우 가장 짧은 방법입니다.

참고로 반대로 다음과 같이 빈 문자열을 연결하면 숫자가 문자열로 작동하도록 할 수 있습니다.

x = 5;
alert(typeof x); //number
x = x+"";
alert(typeof x); //string

누군가에게 도움이되기를 바랍니다


"모든 문자열"이라고 말 했으므로이 문자열도 처리하려는 문자열이라고 가정합니다.

"00012  34 0000432    0035"

따라서 정규식이 갈 길입니다.

var trimmed = s.replace(/\b0+/g, "");

그리고 이것은 "000000"값의 손실을 방지합니다.

var trimmed = s.replace(/\b(0(?!\b))+/g, "")

여기 에서 작동하는 예를 볼 수 있습니다.


나는 자바 스크립트에서 선행 0 (숫자 또는 문자열)을 자르는이 솔루션을 얻었습니다.

<script language="JavaScript" type="text/javascript">
<!--
function trimNumber(s) {
  while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
  return s;
}

var s1 = '00123';
var s2 = '000assa';
var s3 = 'assa34300';
var s4 = 'ssa';
var s5 = '121212000';

alert(s1 + '=' + trimNumber(s1));
alert(s2 + '=' + trimNumber(s2));
alert(s3 + '=' + trimNumber(s3));
alert(s4 + '=' + trimNumber(s4));
alert(s5 + '=' + trimNumber(s5));
// end hiding contents -->
</script>

parseInt(value) or parseFloat(value)

이것은 잘 작동합니다.


이 시도,

   function ltrim(str, chars) {
        chars = chars || "\\s";
        return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
    }

    var str =ltrim("01545878","0");

여기


다음과 같이 간단히 곱해보십시오.

"00123"* 1; // 숫자
"00123"* 1 + ""로 가져옵니다. // 문자열로 가져 오기


"parseInt"함수의 "radix"매개 변수를 사용해야합니다. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt?redirectlocale=en-US&redirectslug=JavaScript%2FReference % 2FGlobal_Objects % 2FparseInt

parseInt('015', 10) => 15

if you don't use it, some javascript engine might use it as an octal parseInt('015') => 0


If number is int use

"" + parseInt(str)

If the number is float use

"" + parseFloat(str)

One another way without regex:

function trimLeadingZerosSubstr(str) {
    var xLastChr = str.length - 1, xChrIdx = 0;
    while (str[xChrIdx] === "0" && xChrIdx < xLastChr) {
        xChrIdx++;
    }
    return xChrIdx > 0 ? str.substr(xChrIdx) : str;
}

With short string it will be more faster than regex (jsperf)


const input = '0093';
const match = input.match(/^(0+)(\d+)$/);
const result = match && match[2] || input;

참고URL : https://stackoverflow.com/questions/8276451/remove-truncate-leading-zeros-by-javascript-jquery

반응형