'Javascript - Regex for double quotes on inch measurements
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:
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?
Solution 1:[1]
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 theJSengine that we're creating aregex.^"*: tells theJSengine to match any"at the start of the string (0 or more).|: acts as the logicalORoperator.(\D)":(\D): creates a matching group of any NON-NUMERIC character.": the literal"character.
g: tells theJSengine to match all the occurrences of thatregex.
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
replacemethod.
Hope i managed to land some help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ths |

