Search code examples
javascriptnode.jsregexbackspace

Insert backspace in regex in camelCased JavaScript string


I have a string in JavaScript and at some places corresponding to a regex (lower case followed by upper case), I would like to insert between upper and lower case the backspace character.

This is an example:

Manufacturer: SamsungWarranty: 12 monthsUnlocking: Any operatorIris scanner: NoScreen size: 5.7 inchesDisplay resolution: 2560 x 1440 pixels

It should become:

Manufacturer: Samsung

Warranty: 12 months

Unlocking: Any operator

Iris scanner: No

Screen size: 5.7 inches

Display resolution: 2560 x 1440 pixels

Solution

  • You can match on /([a-z])([A-Z])/g and replace with "$1\n\n$2", then prepend "Manufacturer: " to the beginning of the string.

    const s = "SamsungWarranty: 12 monthsUnlocking: Any operatorIris scanner: NoScreen size: 5.7 inchesDisplay resolution: 2560 x 1440 pixels";
    const res = "Manufacturer: " + s.replace(/([a-z])([A-Z])/g, "$1\n\n$2");
    console.log(res);