Problem using RegExp and replace [duplicate]

0

I have the following problem, I am replacing text in a paragraph but when I find special characters like (* ,? or others) instead of replacing it, it adds it. I leave the code to see if you can help me.

  

Note: here I only put a small example but it always happens to me that   find a special character.

var search = "LEYES PARA EL OCÉANO*";
var regex = new RegExp(search,'g');
$("#uno").html($("#uno").text().replace(regex,'<span style="color: #FF0000; font-size: 18px;">'+search+'</span>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<p>Texto original:(LEYES PARA EL OCÉANO*)</p>
<p id="uno">LEYES PARA EL OCÉANO*</p>
    
asked by Yoel Rodriguez 27.04.2017 в 17:43
source

1 answer

0

The problem you have is that the character '*' is a reserved character for regular expressions and is interpreted when the replacement is made.

If you are not interested in using regular expressions, you can directly replace:

var search = "LEYES PARA EL OCÉANO*";
    $("#uno").html($("#uno").text().replace(search,'<span style="color: #FF0000; font-size: 18px;">'+search+'</span>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<p>Texto original:(LEYES PARA EL OCÉANO*)</p>
<p id="uno">LEYES PARA EL OCÉANO*</p>

If, on the other hand, you want to use regular expressions, the characters that you do not want the regular expression to replace, you have to escape them.

    var search = "LEYES PARA EL OCÉANO\*";
    var regex = new RegExp(search,'g');
    $("#uno").html($("#uno").text().replace(regex,'<span style="color: #FF0000; font-size: 18px;">'+search.replace('\','')+'</span>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<p>Texto original:(LEYES PARA EL OCÉANO*)</p>
<p id="uno">LEYES PARA EL OCÉANO*</p>
    
answered by 27.04.2017 / 18:45
source