在 javascript 中使用正则表达式在单词的任一侧添加 space
add space on either side of a word using regex in javascript
我想在
的两边添加 space
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*
匹配零个或多个空白字符。
我想在
的两边添加 spaceapple
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*
匹配零个或多个空白字符。