1

I'm trying to replace every '1x' and '1x²' in a mathematical string with 'x' and 'x²' :

var str = '1x² + (1x − 11x)(1x² + 1x²)'; //string to be parsed
var reg = str.replace(/1x/g, 'x');
console.log(reg);

Problem is my regexp also matches numbers like '11x' or '21x', which is obviously not what I want. So my code currently outputs x² + (x − 1x)(x² + x²) instead of x² + (x − 11x)(x² + x²).

I know why I get this behaviour, but I don't know how to fix it. How can I get my regexp to match every 1x and 1x² if and only if they are not preceded by another number like '11x' or 221x²' ?

Hal_9100
  • 773
  • 1
  • 7
  • 17

2 Answers2

6

Use word boundary with regex to avoid matching 1x within 11x.

var str = '1x² + (1x − 11x)(1x² + 1x²)'; //string to be parsed
var reg = str.replace(/\b1x/g, 'x');
console.log(reg);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 1
    Your solution does exactly what I want and taught me a tool I will be using a lot in the future ! Thank you – Hal_9100 Jan 16 '17 at 17:24
0

This seems to be working:

var str = '1x² + (1x − 11x)(1x² + 1x²)'; //string to be parsed
var reg = str.replace(/(^|\D)1x(\D|$)/g,'$1x$2');
poushy
  • 1,114
  • 11
  • 17