I have a problem
I recently worked on a project where my client was able to query order data based on a single date and date range, which I know is exciting!
So the component returns data in the form of the date ‘2019-08-02T00:00:00.000z’. However, I need to use the following format: ‘2019-08-02’. Therefore, I need to separate the time from the date-time string and remove the double quotes from the string.
I’ve tried
Fetching as an expression, or using string intercepts, doesn’t make any sense to me because I’m not satisfied. So I didn’t use those methods!
String.prototype.split () comes into play
To the description of my quick search split method on MDN, it looks like this:
By separating the string at each instance of the specified delimiter string, one very important thing to note about the delimiter is that it must exist in the string
Let’s start with the following example
Since it doesn’t exist in Data, it can’t be split, but what if we adjusted the separator to a similar value, like the letter “A”? Let’s take a look:
So what do we do now?
Never mind, split () makes it easier for you by providing an optional limit argument. Note, however, that once the limit is reached, split stops trying to split the string and serves only what has been split so far. So, assuming we only want our “data” string split by the letter “a”, we get something like this:
Ok, but how does this solve my date and time problem?
Do you remember that I had a date-time string that looked something like this:
‘2019-08-02T00:00.000z’. Now using our new knowledge, I can get the dates in time
The time stampThe part. So HERE’s what I’ll do:
That’s it! But what about the double quotes problem? How can I solve it?
String.prototype.replace () to save!
This is what replace () does, which takes the string you want to use as the first argument and the string you want to introduce as the second argument. So it looks like this:
It uses a double forward slash to replace the string to be deleted. This also allows you to add something like the letter I to indicate that you want the search to be case insensitive, or g to indicate that you want the search to be global, that is, all locations found in the string.
So, to solve our problem, we use it as follows:
So far we have achieved the desired result with only one line of code!
conclusion
I hope it will be helpful. You don’t need to know much about strings before you look at regular expressions, but you can solve string-related problems. Try digging deeper into JavaScript string methods. Please like, share and comment so that more people who need this feature can see it!