1

I have string which contains some date and some comma separated values like this

var a = "1,13,20160308,200500000012016,10,Pending,01-02-2016,1|#|1,13,20160418,200500000012016,10,Pending,08-03-2016,1|#|1,13,20160623,200500000012016,10,Pending,18-04-2016,1|#|1,13,20160803,200500000012016,10,Pending,23-06-2016,1|#|1,13,20160912,200500000012016,10,Pending,03-08-2016,1|#|1,13,20161022,200500000012016,10,Pending,12-09-2016,1|#|1,13,20161129,200500000012016,10,Pending,22-10-2016,1|#|1,13,20170110,200500000012016,10,Pending,29-11-2016,1|#|1,13,20170215,200500000012016,10,Pending,10-01-2017,1|#|15-02-2017 APPEARANCE"

regular expression: /(.)*?01-02-2016(.)*?\|\#\|/igm By using this regular expression i can able to delete unnecessary part in string.

Now i want to change 03-08-3016 (date) dynamically. If i use var date = "01-02-2016" var reg = /(.)*?${date}(.)*?\|\#\|/igm;

If you pring reg in console.log you will get like this below console.log(reg) ----> output: '/(.)?01-02-2016(.)?|#|/igm'

Expected Final output will delete upto 01-02-2016,1|#|

Deepak
  • 1,233
  • 2
  • 8
  • 25

1 Answers1

1

Use this.

var regex="(.)*?01-02-2016(.)*?\\|\\#\\|";
var rx=new RegExp(regex,"igm");
console.log(rx);
//Then when do you want to change,
regex=regex.replace("01-02-2016","03-02-2016");
rx=new RegExp(regex,"igm");
console.log(rx);

JavaScript have 2 methods to make a Regular Expression. 1. write it in slashes // 2. Make from string using new RexExp(string);

If you make it from string, you can give the constraint(" global, incase, etc.") as the second parameter as i did in the above. and also you have to double escape (\) the escape characters.

Sagar V
  • 11,083
  • 7
  • 41
  • 62
  • Yes. i got it man thank you – Deepak Feb 09 '17 at 07:20
  • By using ES6 syntax of template binding we can append variable We can also do this var date = "01-02-2016"; // or dynamic date from db var regex=`(.)*?${date}(.)*?\\|\\#\\|`; var rx=new RegExp(regex,"igm") var output = "asdf 01-02-2016,1|#| done".replace(rx, ''); console.log(output) – Deepak Feb 09 '17 at 07:27
  • Thanks for the info @Deepakrao and will update myself. Sharing will help to gain more knowledge. (y) – Sagar V Feb 09 '17 at 07:29