user544079
user544079

Reputation: 16639

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

I want to add space on either side of

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 

Can we combine all 3 in 1 replace?

Upvotes: 2

Views: 130

Answers (1)

dfsq
dfsq

Reputation: 193301

You can do it with only one regexp:

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

\s* matches zero or more whitespace characters.

Upvotes: 4

Related Questions