简体   繁体   中英

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?

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>');

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM