Search This Blog

2024/03/23

Javascript Regular Expression: Conversion of variable declaration from Singleline to multiline

If you have javascript variable declaration of multiple
variable on single line then you can convert it into multiline
declaration as follows

Code:
var line1 = "const PI = 34.14, EULER = 2.71, GRAVITY = 9.81"
var pattern = /(\w+\s*\=\s*\d+\.\d+)+/g
var result = line1.match(pattern).map((x)=>{ return "const " + x} )
console.log(result)

Output:
[ 'const PI = 34.14', 'const EULER = 2.71', 'const GRAVITY = 9.81' ]

Explanation:
The variables PI,EULER,GRAVITY are declared on single line which is broken
into multiline declaration.

No comments:

Post a Comment