Ameer Hamza
Ameer Hamza

Reputation: 150

How to check the matched character has spaces around in string when replacing it

I have to replace all '&' with 'and' but if string will like this 'Black&air' how I can replace it smartly if '&' has space around then it will only replace with 'and' and if it has no spaces around then ' and '.

Initially i replacing all '&' with 'and'

value.replace(/&/gi, 'and')

Upvotes: 0

Views: 29

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You could optionally include spaces in your regexp and always add them.

const values = ['Black&white', 'Black &white', 'Black& white', 'Black & white']

const replace =  str => str.replace(/\s?&\s?/gi, ' and ')

console.log(values.map(replace))

Upvotes: 2

Related Questions