Reputation: 150
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
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