最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Extract substring of a string before specific character - Stack Overflow

programmeradmin0浏览0评论

I have this string 2022-04-01T09:00

I want to get rid of anything after letter T

I can explode it based on the letter T, and access the first element to get this 2022-04-01.

I wonder if there is a way to do that with JS without having to manually explode and so on...

I have this string 2022-04-01T09:00

I want to get rid of anything after letter T

I can explode it based on the letter T, and access the first element to get this 2022-04-01.

I wonder if there is a way to do that with JS without having to manually explode and so on...

Share Improve this question asked Apr 10, 2022 at 17:10 code-8code-8 58.9k120 gold badges391 silver badges670 bronze badges 1
  • 3 .replace(/T.*$/, '') would work too, or in this case .substr(0, 10) because it seems it's an ISO date that will always have the first 10 characters as YYYY-MM-DD. – CherryDT Commented Apr 10, 2022 at 17:18
Add a ment  | 

1 Answer 1

Reset to default 6

A pretty simple easy to read solution would be to split the string by T and grab the first element like this:

"2022-04-01T09:00".split("T")[0]

Other alternatives include:

  • Using "2022-04-01T09:00".replace(/T.*$/, '') which will replace everything after (and including T) with an empty string.

  • Grabbing the first 10 characters using "2022-04-01T09:00".substring(0, 10)

发布评论

评论列表(0)

  1. 暂无评论