Home > other >  Javascript - Regex for double quotes on inch measurements
Javascript - Regex for double quotes on inch measurements

Time:03-17

Given measurement data like:

2"

3" Contract

When coming back from the server it looks like this:

"\"2\"\"\""

"\"3\"\" Contract\""

e.g. as shown within the image:

enter image description here

I want the data to be displayed as a proper measurement to the user. So:

2"

3" Contract

As shown above

I resorted to complicated regexes to get the second example working (3" Contract) but it would just turn 2" to 2.

let measurement_formatted = value.replace("\"\"", '\"');
measurement_formatted = measurement_formatted.replace(/(^"|"$)/g, '');
measurement_formatted = measurement_formatted.replace("\"", '\"');

How can I develop a proper regex for both cases?

CodePudding user response:

First of all, those \ before the " are just put there to tell you that the " (preceded by a\) is being escaped.

Based on that, the string "\"3\"\" Contract\"" is the same as '"3"" Contract"' because escaping " is no longer needed when the string is delimited by ' character.

To answer, or rather land some help (which I'll always gladly do), you may use the following regex /^"*|(\D)"/g in conjunction with the replace method :

  • / : tells the JS engine that we're creating a regex.
  • ^"* : tells the JS engine to match any " at the start of the string (0 or more).
  • | : acts as the logical OR operator.
  • (\D)" :
    • (\D) : creates a matching group of any NON-NUMERIC character.
    • " : the literal " character.
  • g : tells the JS engine to match all the occurrences of that regex.

The idea here is to tell the replace method to replace all " characters that are preceded by a non-numeric character with that matched non-numeric character and entirely delete the " character.

Here's a live example :

const regex = /^"*|(\D)"/g;

/** $1 : means write down the first matched capturing group */
console.log('"3"" Contract"'.replace(regex, '$1')); // 3" Contract

console.log('2"'.replace(/^"*|(\D)"/g, '$1')); // 2"

Learn more about the replace method.

Hope i managed to land some help.

  • Related