1

I have string date like

'new Date(0,0,0,11,13,16)'

and want to change it to

new Date(0,0,0,11,13,16)

anyone have an idea on it.

thanks

Kalpesh Kashyap
  • 824
  • 11
  • 18
  • It is not clear what it is you want to achieve. If you want to edit some parts of a string you can use slice or replace. if you want your string to become code you can use eval. – rustypaper Jan 17 '19 at 12:06
  • `const string = '\'new Date(0,0,0,11,13,16)\''; string.substring(1, string.length - 1);` – Xatenev Jan 17 '19 at 12:08
  • @Xatenev thanks but not working – Kalpesh Kashyap Jan 17 '19 at 12:09
  • @rustypaper actually my I am trying to add values in HTML string in node js project and rendering html with API response so my date is in string like 'new date(0,0,0,11,13,16)' so I want to remove " ' " from string to make actual date – Kalpesh Kashyap Jan 17 '19 at 12:11
  • Still, it's not clear why you're in this situation to begin with. Its seems like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Right now, it seems that you shouldn't be generating those strings that way. Either generate them without the extra quites or probably better - don't generate *code as a string*. – VLAZ Jan 17 '19 at 12:14
  • @vlaz i am trying to make my array like [ 'Magnolia Room', 'Beginning JavaScript', new Date(0,0,0,12,0,0), new Date(0,0,0,13,30,0) ] and rendring html and my HTML is string html – Kalpesh Kashyap Jan 17 '19 at 12:16
  • That doesn't make the requirement and solution any clearer... – VLAZ Jan 17 '19 at 12:29

3 Answers3

3
var str = 'new Date(0,0,0,11,13,16)';        
var str1 = str.match(/\(.*\)/g)[0];        
str1 = str1.replace('(', '');        
str1 = str1.replace(')', '');        
var dateArr = str1.split(',');        
var updatedDate = new 
Date(dateArr[0],dateArr[1],dateArr[2],dateArr[3],dateArr[4],dateArr[5]);        
console.log(updatedDate);
Mudassir
  • 578
  • 4
  • 6
  • thanks but I want to place date inside [ 'Magnolia Room', 'Beginning JavaScript', new Date(0,0,0,12,0,0), new Date(0,0,0,13,30,0) ] so right now my date is inside quotes like 'new Date(0,0,0,12,0,0,0) ' and I want new Date(0,0,0,12,0,0,0) – Kalpesh Kashyap Jan 17 '19 at 12:21
1

Use regex to solve this problem by matching only numbers. match will return an array of numbers so use the spread operator to set all the parameters to Date.

const res = new Date(...'new Date(0,0,0,11,13,16)'.match(/[0-9]+/g));

console.log(res);
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
0

Theoretically you could use the eval function for that.

Depending on the use, this does propose some security risk though. Read more about this here

If it's possible I would suggest you use another form of date string, e.g. "yyyy-mm-dd" (2019-02-17) and parse it to a date object using the new Date(dateString) constructor (new Date('2019-01-17')).

Linschlager
  • 1,539
  • 11
  • 18