Jordan Davis
Jordan Davis

Reputation: 1520

Simple string manipulation with brackets

Looking for the most efficient way to change this string 000 into [0][0][0].

Upvotes: 0

Views: 61

Answers (3)

isvforall
isvforall

Reputation: 8926

'000'.split('').map(e => `[${e}]`).join('')

Upvotes: 1

rishat
rishat

Reputation: 8376

One more way would be to use regular expression, such that

'000'.replace(/0/g, '[0]')

Upvotes: 4

Andy
Andy

Reputation: 63587

How about using split and join:

'[' + '000'.split('').join('][') + ']'

Or with a regex with replace:

'000'.replace(/\d/g, function (el) { return '[' + el + ']'; })

Upvotes: 4

Related Questions