首页 > 解决方案 > 使用 Javascript 在 URL 中获取 searchTerms 结果查询的双引号

问题描述

var searchTerms = escape(jQuery('input#q').val());
var st = searchTerms.trim();
var res = st.replaceAll("TITLE","ti").replaceAll("%20","%20and%20").replaceAll("AUTHOR","au");

我有上面的代码,需要双引号中的搜索词值作为结果它给出的结果 URL 为:'&query=heartmate%20and%20owens'

但我需要它:'&query="heartmate"%20and%20"owens"'

标签: javascriptjquery

解决方案


最简单的方法是在将值注入请求之前将它们映射到新值。但首先你需要将字符串拆分成单独的术语......

let terms = st.split(' ');

这将返回字符串的各个元素的数组,在空格字符上拆分,然后您可以修剪并附加术语...

terms.map(term => { 
  term.trim(); // <-- this removes all of the whitespace characters, including 
               // space, tab, no-break space, and all the line terminator 
               // characters, including LF, CR, etc. from the beginning and end 
               // of the string
  return '"' + term + '"';
});

您可能会发现需要term在应用 之前检查条件map,这实际上取决于您在做什么。


推荐阅读