EDIT : My code does work - I just had a typo when I was console.logging
. It uses the same technique already found in the answer here .
I have a function that should remove everything after the comma in the string:
function shortenToDate(longDate) {
let newDate = longDate.substring(0, longDate.indexOf(","));
return newDate;
}
^ You just need to take a chunk out of the string from the 0 index to the indexOf()
the first instance of whatever character you wish to remove everything after.
I had also tried:
function shortenToDate(longDate) {
return longDate.substring(longDate.indexOf(0, ","));
}
console.log(shortenToDate(shortenToDate("Friday May 2, 9am")));
Which didn't have any effect. It just returned Friday May 2, 9am
.
You can simply use split and take the 0 th index
const shortenToDate = longDate => longDate.split(',',1)[0]; console.log(shortenToDate("Friday May 2, 9am"))
Problems
In the first snippet you're using
longDate.substring(longDate.indexOf(","), longDate.length -1);
but you want from 0 th index
const shortenToDate = longDate => longDate.substring(0,longDate.indexOf(",")); console.log(shortenToDate("Friday May 2, 9am"))
How about that with String.prototype.split() and Array.prototype.shift() ?
function shortenToDate(longDate) { let newDate = longDate.split(','); return newDate.shift(); } console.log(shortenToDate("Friday May 2, 9am"))
It would probably be easier to use a regular expression - match a comma, followed by any characters, and replace with the empty string:
const shortenToDate = longDate => longDate.replace(/,.*/, ''); console.log(shortenToDate("Friday May 2, 9am"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.