在 JavaScript 中使用正则表达式在单词的任一侧添加空格

add space on either side of a word using regex in javascript

本文关键字:任一侧 添加 空格 单词 正则表达式 JavaScript      更新时间:2023-09-26

我想在

apple

Case1: 
    var str = 'Anapple a day'; // space needed on left
Case 2:
var str = 'An  apple a day; // remove 1 space from left
Case 3:
var str = 'An applea day'; //space needed on right
str = str.replace(/ apple/g, 'apple ');  // adds a space to the right
str = str.replace(/apple /g, ' apple'); // adds a space to the left
str = str.replace(/apple/g, ' apple '); // adds a space on either side 

我们可以将所有 3 合 1 替换结合起来吗?

你可以只用一个正则表达式来做到这一点:

'Anapplea day'.replace(/'s*apple's*/g, ' apple ');

's*匹配零个或多个空格字符。