How to write a single-digit number of years (2-9 years) in full-width format.

Asked 2 months ago, Updated 2 months ago, 1 views

Happy New Year.

I have a quick question,
The code below is a single digit (2-9 years) represented in full-width letters.
Please let me know if there is a more efficient way to write.

<SCRIPT type="text/javascript">
 <!--

   function newYear(){

                       var now = new Date();
                       var Wareki=now.toLocaleDateString("ja-JP-u-ca-Japanese", {era: "long", year: "numeric"}.
                                    replace("year", "")
                                    replace(/(^|[^\d])1(?=$|[^\d])/, '$1 yuan').replace(/(^|[^\d])2(?=$|[^\d])/, '$12').replace(/(^|[^\d])3(?=$|[^\d])/, '$13').
                                    replace(/(^|[^\d])4(?=$|[^\d])/, '$14').replace(/(^|[^\d])5(?=$|[^\d])/, '$15').replace(/(^|[^\d])6(?=$|[^\d])/, '$16').
                                    replace(/(^|[^\d])7(?=$|[^\d])/, '$17').replace(/(^|[^\d])8(?=$|[^\d])/, '$18').replace(/(^|[^\d])9(?=$|[^\d])/, '$19').
                                    replace(/\u200e/g, '').
                                    replace(", "");

                       tartxtReki=Wareki+"year";
                           document.getElementById('newYear').innerHTML = txtReki;

     window.setTimeout("newYear(),1000);
        }
         window.onload=newYear;

 // -- >
 </script>


 <BODY>

<pid='newYear'>/p>

javascript

2022-09-30 14:14

1 Answers

I'm not sure what kind of writing you think is "efficient", but if you only have "full-width conversion of numbers" as a separate function, "repeating almost the same code" can be eliminated.

function toZenDigits(str){
  var result="";
  for (vari=0;i<str.length;++i){
    varch=str.charCodeAt(i);
    if (0x0030<=ch&&ch<=0x0039){
      ch=ch-0x0030+0xFF10;
    }
    result+=String.fromCharCode(ch);
  }
  return result;
}
function newYear(){
  var now = new Date();
  varwareki=now.toLocaleDateString("ja-JP-u-ca-Japanese", {era: "long", year: "numerical")})
    .replace("year", "")
    .place(/(^|[^\d])1(?=$|[^\d])/, '$1 yuan')
    .place(/(^|[^\d])([2-9])(?=$|[^\d])/, function(whole,era,year){returnera+toZenDigits(year);})
    .replace(/\u200e/g, "")
    .replace(", "");

  vartxtReki=wareki+"year";
  document.getElementById('newYear').innerHTML = txtReki;

  window.setTimeout("newYear(),1000);
}
window.onload=newYear;
<spanid="newYear"></span>

There may be a more modern way to write, or a less typeable way to write, but it's a different story from eliminating "repeating almost the same code", so I'll leave it here.


2022-09-30 14:14

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.