Javascript 替换匹配字符时,如何检查字符串中是否有空格

Javascript 替换匹配字符时,如何检查字符串中是否有空格,javascript,string,Javascript,String,我必须将所有的“&”替换为“and”,但如果字符串喜欢这个“Black&air”,我如何才能巧妙地替换它如果“&”周围有空格,那么它将只替换为“and”,如果它周围没有空格,那么“and” 最初,我将所有的“&”替换为“and” value.replace(/&/gi, 'and') 您可以选择在regexp中包含空格并始终添加它们 const value=['Black&white','Black&white','Black&white','Black&white'] const

我必须将所有的“&”替换为“and”,但如果字符串喜欢这个“Black&air”,我如何才能巧妙地替换它如果“&”周围有空格,那么它将只替换为“and”,如果它周围没有空格,那么“and”

最初,我将所有的“&”替换为“and”

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

您可以选择在regexp中包含空格并始终添加它们

const value=['Black&white','Black&white','Black&white','Black&white']
const replace=str=>str.replace(/\s?&\s?/gi,'和')

console.log(values.map(replace))
您可以选择在regexp中包含空格并始终添加它们

const value=['Black&white','Black&white','Black&white','Black&white']
const replace=str=>str.replace(/\s?&\s?/gi,'和')

console.log(values.map(replace))
在任意一侧的正则表达式中添加空间?我如何做到?在任意一侧的正则表达式中添加空间?我如何做到?