javascript - 如何查找发生语法错误的原因以及如何实现全局化格式

标签 javascript jquery html jquery-globalize

这是我的代码,

Globalize.format(50.635676576567%, 'n2')

它抛出语法错误,因为 % 已添加到数字中。但我需要将输出显示为 50.64%。如何实现通用方式{注意:符号可以是任何字符或特殊数字......}

示例:

Globalize.format(50.635676576567%, 'n2') = 50.64%
Globalize.format(50.635676576567C, 'n2') = 50.64C
Globalize.format(50.635676576567@, 'n2') = 50.64@
Globalize.format($50.635676576567, 'n2') = $50.64
Globalize.format(#50.635676576567, 'n2') = #50.64
Globalize.format(50.635676576567world, 'n2') = 50.64 world

如何实现?

最佳答案

请尝试此代码。您必须拆分字符和数字才能执行全局化格式

var str = "Globalize.format(50.635676576567world, 'n2') Globalize.format($50.635676576567, 'n2') ",
substr;

while (str.indexOf('Globalize.format(') >= 0) {
   substr = str.substring(str.indexOf('Globalize.format('), str.indexOf(")") + 1);
   var calculate = substr.substring(substr.indexOf('(') + 1, substr.indexOf(",")),
   character = calculate.replace(/[0-9.]/g, ''),
   numberic = calculate.replace(/[^\d.]/g, ''),
   index = calculate.indexOf(character),
   formatedString = substr.replace(character, "");
   if (index == 0)
      formatedString = character + eval(formatedString);
   else
      formatedString = eval(formatedString) + character;
   str = str.replace(substr, formatedString);
}
console.log(str);

希望这对您有帮助。

关于javascript - 如何查找发生语法错误的原因以及如何实现全局化格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33908999/

相关文章:

javascript - 单击 introJS 中的元素转到下一步

php - ajax只工作一次然后点击后停止

javascript - 使用 jquery 从一个对象中选择文本值

javascript - 通过 javascript 在同一窗口中加载页面

css - 嵌套的 DIV 不服从自动

javascript - js功能无法实现跨浏览器兼容

javascript - JQuery 文本编辑器粘贴而不格式化

html - 将一个 div 的宽度调整到另一个具有左右填充的 div 中

javascript - 在对象数组中查找多个值的 d3 范围

javascript - 当选择选项的值不为空/NULL 时,jQuery 执行某些操作