Igor Lukashov
Igor Lukashov

Reputation: 47

Regular expression and wrap minus

Here my code.

var string = 'number1 + number2 - number3';
var operators = [
   {o: '+', regex: '\\+'},
   {o: '-', regex: '\\-'}
];

$.each(operators, function(i, operator){
    string = string.replace(
      new RegExp(operator.regex, "g"),
      '<span class="formula-operator">' + operator.o + '</span>'
    );
});

My CSS-class is replaced twice. How should I change my regex?

Upvotes: 1

Views: 71

Answers (2)

Me.Name
Me.Name

Reputation: 12544

If you don't need the operators array itself, you could use a single regex:

string = string.replace(/[+-]/g, operator => '<span class="formula-operator">' + operator + '</span>');

(Otherwise this expression could be build based on the operators themselves)

PS, the second replacement happens because you have a match (-) inside <span class="formula-operator">


edit: An example with dynamic building of the expression:

var string = 'number1 + number2 - number3';
var operators = ['+','-'];

string = string.replace(
            new RegExp('[' + operators.join('') + ']', "g"), 
      o => '<span class="formula-operator">' + o + '</span>');

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627129

You can use lookaheads that will make sure we are not inside a span tag.

var operators = [ 
   {o: '+', regex: '\\+(?![^<]*</span>)'}, 
   {o: '-', regex: '\\-(?![^<]*</span>)'} 
];

The (?![^<]*</span>) lookahead will fail a match if the math operator is followed by zero or more characters other than < ([^<]*) followed by </span>.

This will not work with nested <span> tags, you will need a DOM parser for that.

Upvotes: 1

Related Questions