2

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?

1 Answer 1

4

You can do it with only one regexp:

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

\s* matches zero or more whitespace characters.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.