简体   繁体   中英

How to Remove Special Characters in this Javascript Code

How do I remove special characters in the specific code below? I've been trying to use replace with var = t, but it has not worked properly. When a person enters a comma in the number they want converted to words, it cuts the sentence.

Thanks!

var o=new Array("diez", "once", "doce", "trece", "catorce", "quince", "dieciséis", "diecisiete", "dieciocho", "diecinueve", "veinte", "veintiuno", "veintidós", "veintitrés", "veinticuatro", "veinticinco", "veintiséis", "veintisiete", "veintiocho", "veintinueve");
var u=new Array("cero", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve");
var d=new Array("", "", "", "treinta", "cuarenta", "cincuenta", "sesenta", "setenta", "ochenta", "noventa");
var c=new Array("", "ciento", "doscientos", "trescientos", "cuatrocientos", "quinientos", "seiscientos", "setecientos", "ochocientos", "novecientos");

function toWords(n)
{ 
  var n=parseFloat(n).toFixed(2);
  var p=n.toString().substring(n.toString().indexOf(".")+1);
  var m=n.toString().substring(0,n.toString().indexOf("."));
  var m=parseFloat(m).toString().split("").reverse();
  var t=" ";


  for (var i=0; i<m.length; i+=3)
  {
    var x=t;

    var b=m[i+1]!=undefined?parseFloat(m[i+1].toString()+m[i].toString()):parseFloat(m[i].toString());

    t=m[i+2]!=undefined?(c[m[i+2]]+" "):"";
    t+=b<10?u[b]:(b<30?o[b-10]:(d[m[i+1]]+(m[i]=='0'?"":(" y "+u[m[i]]))));
    t=t=="ciento cero"?"cien":t;
    if (2<i&&i<6)
      t=t=="uno"?"mil ":(t.replace("uno","un")+" mil ");
    if (5<i&&i<9)
      t=t=="uno"?"un millón ":(t.replace("uno","un")+" millones ");
    t+=x;
    //t=i<3?t:(i<6?((t=="uno"?"mil ":(t+" mil "))+x):((t=="uno"?"un millón ":(t+" millones "))+x));
  }

  return t;
}

u have n= parseFloat(n) ... that will consider coma as floating point, use n =parseFloat(n.replace(',','')); but this is incorrect removal of comma

ParseFloat doesn't support thousand separators. If you want to support user input containing such separators, you'll have to manually strip them off.

function toWords(n)
{ 
  var n=parseFloat(n.replace(',','')).toFixed(2);
  ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM