Pavel Vanchugov Pavel Vanchugov - 5 days ago 6
jQuery Question

replace line of js code with special characters and spaces

I have lines of text in textarea and sequential divs, representing this lines.
I am trying to reorder divs and make lines of text reorder accordingly.

Divs have the same id as indexies of text lines in array.

Right now i stuck at deleting lines.
Lines can be deleted if it's a simple text. But in my case it's a js code. And it doesn't work for some reason.

Working code http://codepen.io/one2gov/pen/eBGqBR?editors=1111 (lower selectedDivNumber to check it)

var selectedDivNumber = 2;
var linesArray = ["line0;", "line1;", "tl.to(abstract_m, 13, {x:'1327', y:'117', autoAlpha:1, delay:4}, 'num_sound');"];
var arrayNumber = linesArray[selectedDivNumber];

textArea = $("#fname").val();
textArea = textArea.split(';');

arrayNumber = new RegExp(arrayNumber,'g');
$("#fname").html($("#fname").html().replace(arrayNumber, "something else;"));


I tried to use in .replace variable arrayNumber, and now i turned it into new RegExp but no luck.

Answer

The string you're trying to replace is breaking the regular expression because of special characters like { and (.

I use a RegExp escape function for this:

RegExp.escape= function(s) {
  return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); //replace special characters so RegExp won't break
};

//tl.to(abstract_m, 13,  {x:'1327', y:'117', autoAlpha:1, delay:4}, 'num_sound');

var selectedDivNumber = 2;
var linesArray = ["line0;", "line1;", "tl.to(abstract_m, 13,  {x:'1327', y:'117', autoAlpha:1, delay:4}, 'num_sound');"];
var arrayNumber = linesArray[selectedDivNumber];

textArea = $("#fname").val();
textArea = textArea.split(';');   

arrayNumber = new RegExp(RegExp.escape(arrayNumber),'g'); //escape with RegExp.escape
$("#fname").html($("#fname").html().replace(arrayNumber, "something else;"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id = "fname" = rows="4" cols="50">
line0;
line1;
tl.to(abstract_m, 13,  {x:'1327', y:'117', autoAlpha:1, delay:4}, 'num_sound');
</textarea>

Comments