killertoge
killertoge

Reputation: 345

How can I replace a specific part of a string?

The string looks like 2017-08-01T00:00:00.000Z

I want to keep the date 2017-08-01, I would prevent to work with replaceAT!

date.replace(date.substr(date.indexOf("T00")),""); 
// I also tried RegExp like +"/g"

Upvotes: 1

Views: 100

Answers (6)

some
some

Reputation: 49632

If you only want the first part of the string, you can use slice, substr or substring:

var date = "2017-08-01T00:00:00.000Z";
var part = date.slice(0,10);
// or date.substr(0,10);
// or date.substring(0,10);

Upvotes: 1

Stanislav Doroshin
Stanislav Doroshin

Reputation: 81

var d = new Date('2017-08-01T00:00:00.000Z');

d.getFullYear();   // 2017
d.getMonth() + 1;  // 8
d.getDate();       // 1

Upvotes: 4

Polaris
Polaris

Reputation: 712

If i understand you correct, a way like this should be right...

var str = '2017-08-01T00:00:00.000Z';
alert(str.substr(0, 10));

Upvotes: 1

jarbaspsf
jarbaspsf

Reputation: 37

Why not just use substring()?

var date = date.substring(0,10)

Upvotes: 1

Jaydip Jadhav
Jaydip Jadhav

Reputation: 12309

What about this

"2017-08-01T00:00:00.000Z".split("T00")[0]

Upvotes: 3

kukkuz
kukkuz

Reputation: 42360

Use regex expression /T.*$/ - see demo below:

console.log("2017-08-01T00:00:00.000Z".replace(/T.*$/,''));

Upvotes: 2

Related Questions