osfar
osfar

Reputation: 413

Regular expression to replace only if it has numeric value before

I want to write a regular expression to replace x and X values with an underscore _ only if x and X are if it's surrounded with digits, or preceded or followed by digits.

For example:

OFE_PALLET_120X92 will be OFE_PALLET_120_92
OFX_PALLET_120X92 will be OFX_PALLET_120_92

This is my initial code:

sRegExInput = new RegExp('[xX]', 'g');
result =    result.replace(sRegExInput ,'_');

How to achieve that?

Upvotes: 1

Views: 85

Answers (3)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Use \\d in a constructor:

var result = 'OFE_PALLET_120X92 will be OFE_PALLET_120_92';
var sRegExInput = new RegExp('(\\d)x', 'gi');
result = result.replace(sRegExInput ,'$1_');
console.log(result);

Explanation

--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    \d                       digits (0-9)
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  x                        'x' or 'X' due to i flag

The $1 refers to the captured substring.

Upvotes: 1

KodeFor.Me
KodeFor.Me

Reputation: 13511

With the provided regular expression, I do match the pattern as:

  1. Find one or more digits,
  2. Followed by x or X
  3. Followed by one or more digits.

Then in the replace statement, I use the $1 to put in the replacement the first group of found digits, and the $3 to put in the replacement the last group of found digits.

The map in the entries variable used just to simplify the code. This has nothing to do with the regex.

var entries = [
    'OFE_PALLET_120X92',
    'OFX_PALLET_120X92'
];

var result = entries.map(
    function(entry) {
        return entry.replace(/(\d+)([xX])(\d+)/g ,'$1_$3');
    }
);

console.log(result);

Run the code snippet to test the output :)

Upvotes: 1

Aplet123
Aplet123

Reputation: 35512

You can use the following regex:

"OFX_PALLET_120X92".replace(/(\d)x/ig, "$1_")
// "OFX_PALLET_120_92"

Essentially, it finds a number, captures it, then finds an X, and replaces it with the captured number ($1) and an underscore.

Upvotes: 1

Related Questions