Every JavaScript developer should know two string functions

Every JavaScript developer should know two string functions

The problem i encountered

I recently worked on a project where my client was able to query order data based on a single date and date range. I know this is very exciting!

Therefore, the data returned by the component is the date in this form "'2019-08-02T00:00:00.000Z"'. However, I need to use the following format: '2019-08-02'. Therefore, I will need time and date time string separately, and from a string delete double quotes.

I tried before

Use the form of expression to obtain, or use string interception, but it does not make any sense to me, because I am not satisfied. So I did not use these methods!

String.prototype.split() comes into play

To my quick search split method description on MDN, it is as follows:

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 first look at the following example

Because it is not in the data, it cannot be split, but what if we adjust the separator to a similar value, such as the letter "a"? Let's see:

What should we do now?

It doesn't matter, split() can be convenient for you by providing an optional limit parameter. But it should be noted that once the limit is reached, split will stop trying to split the string and only provide what has been separated so far. Therefore, suppose we only want our "data" string to be split only by the letter "a", then we will get the result as shown below:

Okay, but how does this solve my date and time problem?

Do you remember, I have a date and time string that looks like this: '"2019-08-02T00:00:00.000Z"' . Now using our new knowledge, I can get the timestamp part of the date and time . So I will do this:

So far it is solved! But what about the double quote problem? How can I solve it?

String.prototype.replace() comes to the rescue!

This is the role of replace() , which takes the string you want to use as the first parameter and the string to be introduced as the second parameter. So it looks like this:

It uses double forward slashes to replace the string to be deleted. This also allows you to add things like the letter i to indicate that you want the search to be case-insensitive, or add a g to indicate that you want the search to be global, that is, all positions found in the string.

Therefore, to solve our problem, we use it as follows:

So far we have achieved the desired result with only one line of code!


I hope it helps you. Before looking for regular expressions, you don't need to know a lot but can solve string-related problems, please try to study JavaScript string methods in more depth. Please like, share and comment so that more people who need this feature can see it!