Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中使用正则表达式在单词的两侧添加空格_Javascript_Regex - Fatal编程技术网

在javascript中使用正则表达式在单词的两侧添加空格

在javascript中使用正则表达式在单词的两侧添加空格,javascript,regex,Javascript,Regex,我想在每一侧添加空间 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 ');

我想在每一侧添加空间

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替换组合起来吗?

您只需一个regexp即可:

'Anapplea day'.replace(/\s*apple\s*/g, ' apple ');
\s*
匹配零个或多个空白字符