Javascript replaces characters

I want to replace all the characters "-", ":" and spaces from the line that appears in this format:

"YYYY-MM-DD HH:MM:SS" 

sort of:

 var date = this.value.replace(/:-/g, ""); 
+6
source share
4 answers

You were close: "YYYY-MM-DD HH:MM:SS".replace(/:|-/g, "")

+7
source

/:-/g means ":" followed by "-" . If you put characters in [] , it means ":" or "-" .

 var date = this.value.replace(/[:-]/g, ""); 

If you want to remove spaces, add \s to the regular expression.

 var date = this.value.replace(/[\s:-]/g, ""); 
+2
source

You may have regex probably:

 /[\s:-]/g 

Usage example:

 "YYY-MM-DD HH:MM:SS".replace(/[\s:-]/g, ''); 

[] blocks any of the contained characters.

In it, I added a \s pattern that matches space characters, such as a space , and the \t tab (not sure if you need bookmarks and new lines, so I went with tabs and skipped the translation lines).

It seems you have already guessed that you want a g lobal match, which allows the regular expression to continue to replace found matches.

+1
source

You can use either a character class or | (or):

 var date = "YYYY-MM-DD HH:MM:SS".replace(/[:-\s]/g, ''); var date = "YYYY-MM-DD HH:MM:SS".replace(/:|-|\s/g, ''); 
+1
source

Source: https://habr.com/ru/post/895273/


All Articles