0

My text is

<DIV STYLE="text-align:Left;font-family:Segoe UI;font-style:normal;font-weight:normal;font-size:12;color:#000000;"><P STYLE="font-family:Arial;margin:0 0 0 0;"><SPAN STYLE="font-family:Segoe UI;"><SPAN>{firstname} will continue to learn high frequency words, try to remember words and us them in their writing. {firstname} always uses correct spacing in their writing and attempts to use punctuation.</SPAN></SPAN></P></DIV>

So now i want to replace the {firstname} at index 202 with {firstname_C}

My code here doesnot work

var endIndex = 202;
var pattern = new RegExp("({firstname}{" + endIndex + "})", "g");
                commentString = commentString.replace("({firstname})/g", "{firstname_C}");

Referred to this code from here

Samra
  • 1,815
  • 4
  • 35
  • 71

1 Answers1

0

{ and } are special characters in regexp, you have to escape them in pattern:

Try:

commentString.replace(/\{firstname\}/g, '{firstname_C}')
Chris Lam
  • 3,526
  • 13
  • 10
  • i tried your solution: commentString = commentString.replace(/\{firstname\}{202}/g, "{firstname_C}"); – Samra Jun 15 '17 at 03:07
  • That works for me perfectly: `'{firstname} will continue to learn high frequency words, try to remember words and us them in their writing. {firstname} always uses correct spacing in their writing and attempts to use punctuation.'.replace(/\{firstname\}/g, '{firstname_C}')` – Chris Lam Jun 15 '17 at 03:10
  • problem is i need to replace at a specific index only..you have not included index 202 in your code – Samra Jun 15 '17 at 03:11
  • if you know the index already, why regexp? https://stackoverflow.com/questions/2236235/how-to-replace-a-string-at-a-particular-position – Chris Lam Jun 15 '17 at 03:13
  • c'mon I am just trying to help. You determined the SPECIFIC index in whatever way you did, so THE INDEX IS KNOWN DURING RUNTIME and you know the EXACT LENGTH of the text you going to replace. Try figuring the solution yourself without regexp. – Chris Lam Jun 15 '17 at 03:41