I have a sentence which looks like below
term = "How much new sales in new"
Say I get a some suggestions like New York, New Delhi, Papua New Guinea
and I select New York
.
choice = "New York"
Now I need to ensure that any latest substring that matches the selection is replaced with the selection.
So ideally my string should now become
term = "How much new sales in New York"
So this is what I do
terms = term.split(/\s+/g)
choice_terms = choice.split(/\s+/g)
terms.pop() //remove the last substring since this is what the user typed last
check_terms = terms
// get the latest instance of first term of the selection
if(user_choice_terms.length > 1) {
if(check_terms.lastIndexOf(user_choice_first_term) !== -1) {
last_index = check_terms.lastIndexOf(user_choice_first_term)
check_terms.splice(-last_index) //remove anything after the matched index
check_terms.push(...user_choice_terms) //add the selected term
return check_terms
}
}
But this doesn't seem like a reliable solution and I would rather use a regex
. The user may also type like this
term = "How much new sales in new yo"
Here I am guaranteed to get a suggestion New York
against yo
and should be replaced with New York
Is there any regex
solution to ensure the latest substring match is completely replaced with the selection?
Note: I am using jquery ui autocomplete