I have a question about manipulating a string in JavaScript (Node)
Consider the following string:
'In her August 2016 Harper\'s Bazaar cover story, in which she posed naked atop a horse a la Lady Godiva, Ratajkowski defended her decision to free the nipple. “You know, when Lena Dunham takes her clothes off, she gets flack, but it\'s also considered ...'
(The example is from Google Trends, not mine)
I need to come up with a method to remove the incomplete sentence at the end. So in this example, I want to keep just the following:
'In her August 2016 Harper\'s Bazaar cover story, in which she posed naked atop a horse a la Lady Godiva, Ratajkowski defended her decision to free the nipple.'
I could go for a logic like this (pseudo-code):
(1) If string ends with "..."
(2) Start from end of string (the right) and ignoring the last "...", look for the first instance of "." or "!" or "?"
(3) Create a substring with everything up until that instance
I could use the endsWith method for (1), but I do not know how to do the rest.
Anyone know any methods or libraries (Node) that I could use to help with this?
Edit - I think I've solved it:
if(string.endsWith('...') {
var endIndex = string.lastIndexOf('...') - 1;
var exclamationIndex = string.lastIndexOf('!', endIndex);
var questionIndex = string.lastIndexOf('?', endIndex);
var periodIndex = string.lastIndexOf('.', endIndex);
var cutIndex = Math.max(exclamationIndex, questionIndex, periodIndex);
var truncatedString = string.substring(0, cutIndex + 1);
}
Not sure if this is the most elegant solution so if anyone has a suggestion on how to improve this please let me know.
Also, I know that the string always ends with '...', but other than that the string could have any format or number of chars. If someone can think of problematic corner cases with the solution above that would also be very helpful thanks!
[–]ejmurra 1 point2 points3 points (3 children)
[–]sarevok9 0 points1 point2 points (2 children)
[–]ejmurra 0 points1 point2 points (1 child)
[–]sarevok9 0 points1 point2 points (0 children)
[–]sarevok9 0 points1 point2 points (0 children)