Zahidur Rahman
Zahidur Rahman

Reputation: 1718

Insert a space between a numerical number and character

I have an mathematical equation

var equation="(4+5.5)*3+4.5+4.2";

When i do

equation.split('').join(' ');

It gets output, space between each character.

( 4 + 5 . 5 ) * 3 + 4 . 5 + 4 . 2

How to do insert a space between numerical number and alpha character?

Sample Output :

( 4  +  5.5 ) *  3  +  4.5  +  4.2

Have anyone can help me how to figure out, thanks in advance.

Upvotes: 3

Views: 400

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386520

You could pad the operators.

var string = "(4+5.5)*3+4.5+4.2",
    result = string.replace(/[+\-*/]/g, ' $& ');

console.log(result);

Parentheses with spaces.

var string = "(4+5.5)*3+4.5+-4.2",
    result = string
        .replace(/[+\-*/()]/g, ' $& ')
        .replace(/([+\-*/]\s+[+\-])\s+/, '$1')
        .replace(/\s+/g, ' ').trim();

console.log(result);

Upvotes: 5

CertainPerformance
CertainPerformance

Reputation: 370629

You might use a regular expression and match either numeric tokens (digits, optionally followed by a period and other digits), or match any character. Then, join by a space:

const equation = "(4+5.5)*3+4.5+4.2";
const output = equation
  .match(/\d+(?:\.\d+)?|./g)
  .join(' ');
console.log(output);

Upvotes: 2

Related Questions