Reputation: 119
String I get is
["2021-01-13T09:45:48.046Z","2021-01-14T09:45:48.096Z","2021-01-15T09:45:48.099Z"]
Here I want to delete substring from T to Z for converting to this form:
["2021-01-13","2021-01-14","2021-01-15"]
I did like that but it replaces only the first string and deletes others, How can I do this separately for each
notFound=notFound.replace(/\T.*\Z/g, '');
Can I do this with the javascript substring function?
Upvotes: 4
Views: 245
Reputation: 163342
If the strings are always in the same format, you could turn the string into an array and then also split on T
and take the first part.
const str = '["2021-01-13T09:45:48.046Z","2021-01-14T09:45:48.096Z","2021-01-15T09:45:48.099Z"]';
let result = JSON.parse(str).map(s => s.split("T")[0]);
console.log(result);
For a specific match, you could use a pattern to match the datetime like format ^(\d{4}-\d{2}-\d{2}T)\d{2}:\d{2}:\d{2}\.\d{3}Z$
and replace with capturing group 1.
const str = '["2021-01-13T09:45:48.046Z","2021-01-14T09:45:48.096Z","2021-01-15T09:45:48.099Z"]';
let result = JSON.parse(str).map(s =>
s.replace(/^(\d{4}-\d{2}-\d{2})T\d{2}:\d{2}:\d{2}\.\d{3}Z$/, "$1")
);
console.log(result);
Upvotes: 1
Reputation: 386578
You could replace with an nongready search.
const
data = '["2021-01-13T09:45:48.046Z","2021-01-14T09:45:48.096Z","2021-01-15T09:45:48.099Z"]',
result = data.replace(/T.*?Z/g, '');
console.log(result);
Upvotes: 4
Reputation: 404
You've got it right, just do a loop like this:
["2021-01-13T09:45:48.046Z","2021-01-14T09:45:48.096Z","2021-01-15T09:45:48.099Z"].map(s => s.replace(/\T.*\Z/g, ''));
Upvotes: 2
Reputation: 5237
I think you mean you have an array initially, rather than a string, in which case, this answer should suffice.
You can use Array.prototype.map()
to do the replacement on each element of the array.
const x = ["2021-01-13T09:45:48.046Z", "2021-01-14T09:45:48.096Z", "2021-01-15T09:45:48.099Z"];
const y = x.map(e => {
return e.replace(/T.*Z/, "");
});
console.log(y);
Side note: you don't need to escape the T
and Z
in the regular expression, and the global flag is redundant.
Upvotes: 1
Reputation: 986
Because you said String so you will have to parse it.
const str = '["2021-01-13T09:45:48.046Z","2021-01-14T09:45:48.096Z","2021-01-15T09:45:48.099Z"]';
let x = JSON.parse(str).map((e) => e.replace(/\T.*\Z/g, ''));
console.log(x);
Upvotes: 3