在JavaScript中使用正则表达式自动完成最后一个不完整的短语

在JavaScript中使用正则表达式自动完成最后一个不完整的短语,javascript,regex,string,jquery-ui-autocomplete,Javascript,Regex,String,Jquery Ui Autocomplete,我有一个句子如下所示 term = "How much new sales in new" 假设我得到一些建议,比如纽约、新德里、巴布亚新几内亚,然后我选择纽约 choice = "New York" 现在,我需要确保匹配该选择的任何最新子字符串都被替换为该选择 因此,理想情况下,我的字符串现在应该是 term = "How much new sales in New York" 这就是我要做的 terms = term.split(/\s+/g) choice_terms = choic

我有一个句子如下所示

term = "How much new sales in new"
假设我得到一些建议,比如纽约、新德里、巴布亚新几内亚,然后我选择纽约

choice = "New York"
现在,我需要确保匹配该选择的任何最新子字符串都被替换为该选择

因此,理想情况下,我的字符串现在应该是

term = "How much new sales in New York"
这就是我要做的

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
    }
 }
但这似乎不是一个可靠的解决方案,我宁愿使用
regex
。用户也可以这样键入

term = "How much new sales in new     yo"
在这里,我保证会得到一个针对
yo
的建议
newyork
,应该被
newyork

是否有任何
regex
解决方案来确保最新的子字符串匹配完全替换为所选内容


注意:我使用的是
jquery ui自动完成

您可以创建一个模式,该模式将匹配
选项的所有可能前缀
,所有空格替换为
\s+
模式以匹配一个或多个空格,并在模式末尾添加
$
,以仅匹配字符串:

/N(?:e(?:w(?:\s+(?:Y(?:o(?:r(?:k)?)?)?)?)?)?)?$/i
它将使用
New
York
之间的任意数量的空格来匹配
N
Ne
New
等,并且由于
$
的原因,仅在字符串的末尾进行匹配

请参阅JavaScript演示:

const make_前缀=(字符串)=>{
设s=string.charAt(0);

对于(让我=1;我在正则表达式中去掉
$
的含义。@DanielF当然可以,但即使我检测到
新的yo
,我也不明白如何处理它。
(\w+?\*\w+\*)$
其中第1组(
\1
)将是您的查询词,在数据库中搜索之前,您将所有连续的空格替换为一个空格。这个解决方案很好。但您能否检查替换是否成功?换句话说,前缀是否匹配。如果前缀不匹配,我计划触发另一段代码。@SouvikRay you可以使用
if(regex.test(term)){term=term.replace(regex,choice);}else{/*如果不匹配,则返回*/}
您好!正则表达式有问题。如果我的术语是
名称
,选项是
尾端名称
,那么最后的术语是
名称尾端名称
,而不是
名称尾端名称
。您能检查一下吗?@SouvikRay在我看来,在这种情况下应该没有匹配项,您需要在单词边界处进行匹配,
const r>egex=new RegExp(“\\b”+make_前缀(选项)。替换(/\s+/g,\\s+')+“$”,“i”);
您好,我已经尝试过这个,这个对我有用。再次感谢!