There is a code:

var task; task = '(X^2+X^2)+X^2'; task = task.replace(/(^|\+)X\^2\b/g, '+1X^2'); 

at the output, the task will be (X^2+1X^2)+1X^2 .
How to make it so that at the output task was equal to (+1X^2+1X^2)+1X^2 ? I just need to do so that he read the bracket, but did not remember it.

    1 answer 1

     var task; task = '(X^2+X^2)+X^2'; task = task.replace(/(?:^|\+)?X\^2\b/g, '+1X^2'); 

    (?:) - non-memorable brackets

    You in the first case have neither a degree nor a plus, therefore it does not take it into account. Need to add a sign after the bracket ? whatever the expression accepts regularly even if these characters are not present

    • I need not only memorize '(', everything else should be remembered. - Alex3214
    • @ Alex3214, I do not understand. - Yuri
    • Well, in general, I just tried it, but it still does not help (Are there any other ways? - Alex3214
    • @ Alex3214, maybe so? (?:^|\+)?X\^2\b - Yuri
    • Thanks, it helped. Can you explain what is happening there, why do you need another question mark? - Alex3214