我想在两边增加空间
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*
匹配零个或多个空格字符。