javascriptjqueryhtmljquery-globalize

how to find why the syntax error occur & how to achieve a globalize format


Here is my code,

Globalize.format(50.635676576567%, 'n2')

it throw syntax error because of % has been added in number. but i need to show the output as 50.64%. how to achieve generic way{note: the symbol can be anything like character or special number anything...}

Example:

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

how to achieve?


Solution

  • Please try this code. You must split the characters and numbers to perform globalize format

    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);
    

    Hope this will help you.