1
 var str='The_Andy_Griffith_Show'; // string to perform replace on
 var regExp1=/\s|[A-Z]/g;
 var regExp2=/[^A-Z]/g;            // regular expression
 var str2 =str.replace(regExp2,regExp1); 
 // expected output: The_ Andy_ Griffith_ Show

I want to replace all the first capital letters of a string with a space and that same letter, and if that's not possible is there a workaround?

2

3 Answers 3

1

If you want to add a space before any captial letter, it is enough to use

var str='The_Andy_Griffith_Show';
str = str.replace(/[A-Z]/g, ' $&')
console.log(str); // => "  The_ Andy_ Griffith_ Show"

Here, /[A-Z]/g matches all ASCII uppercase letters and $& is a backreference to the whole match value.

If you want to only add a space before the first capital letter in a word, you need to use capturing groups and backreferences to thier values in the replacement pattern:

var str='The_Andy_Griffith_Show'; // string to perform replace on
str = str.replace(/(^|[^A-Z])([A-Z])/g, '$1 $2')
console.log(str); // => "  The_ Andy_ Griffith_ Show"

Remove ^| if you do not want to add space before a capital letter at the string start (i.e. use /([^A-Z])([A-Z])/g).

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

Comments

0

Just an alternative to the other answers.
To get that expected result you could just match the non-uppercases that are followed by an uppercase character, then replace them with the match $& and a space.

For example:

var str='The_Andy_Griffith_Show';
str = str.replace(/[^A-Z](?=[A-Z])/g, '$& ')
console.log(str);

Or simply match those uppercases followed by an uppercase character.

var str='The_Andy_Griffith_Show';
str = str.replace(/[_](?=[A-Z])/g, '$& ')
console.log(str);

Comments

0

To add space to all occurrences of capital letters:

var str = 'The_Andy_Griffith_Show',
    str2 = str.replace(/[A-Z]/g, letter => ` ${letter}`);
    
console.log(str2);

Notice that if you want no to add space to the first letter occurrence, just use the regular expression /(?!^)[A-Z]/g.

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.