KMX
KMX

Reputation: 2691

How to use regular expressions to insert space into a camel case string

I am using the following regular expression to insert spaces into a camel-case string

var regex = /([A-Z])([A-Z])([a-z])|([a-z])([A-Z])/g;

Example usage

var str = "CSVFilesAreCoolButTXTRules";
str = str.replace( regex, '$1$4 $2$3$5' );
// "CSV Files Are Cool But TXT Rules"

This works fine, but I also want to put spaces before and after any numbers in the string, though I don't want space inserted between individual digits, and if a number is preceded by a $ then the space should go before it, and not the number.

I also want to remove any characters apart from numbers, letters, the $ sign and a dot . within a number.

For example,

MRRPLowPriceUSD$10.10HighPriceUSD$1998.59595CommentsNoChangeReportedNTPL1001KSE-100INDEX

should become

MRRP Low Price USD $10.10 High Price USD $1998.59595 Comments No Change Reported NTPL 1001 KSE 100 INDEX

Note that the - was removed.

Any assistance would be appreciated.

Related: putting-space-in-camel-case-string-using-regular-expression.

Upvotes: 5

Views: 3750

Answers (1)

speakr
speakr

Reputation: 4209

Try this regex and replace using positive look-ahead:

var regex = /([^A-Za-z0-9\.\$])|([A-Z])(?=[A-Z][a-z])|([^\-\$\.0-9])(?=\$?[0-9]+(?:\.[0-9]+)?)|([0-9])(?=[^\.0-9])|([a-z])(?=[A-Z])/g;
var str = "CSVFilesAreCool123B--utTXTFoo12T&XTRules$123.99BAz";
str = str.replace(regex, '$2$3$4$5 ');
// CSV Files Are Cool 123 B ut TXT Foo 12 T XT Rules $123.99 B Az

(RegExr)

Upvotes: 10

Related Questions