如何根据搜索字符串在JavaScript中获取所有建议的字符串

huangapple go评论91阅读模式
英文:

How to get all the suggested string on the basis of search string in javascript

问题

I have two string, one which contains all the values of countries and second string which I entered when I'm searching for country. Now, I want all the results which contains "In" like result will be
India, Indonesia

as I have search for IN

  1. const s2 = "India, Australia,Canada,Luxembourg,Singapore,Switzerland,United States of America, Indonesia";
  2. const s1 = "In";
  3. const findString = (s1, s2) => {
  4. if(s2.includes(s1.charAt(0).toUpperCase() + s1.slice(1))){
  5. return s1;
  6. } else {
  7. return null;
  8. }
  9. }

this function returning me "IN" but I want "India, Indonesia" as result

英文:

I have two string, one which contains all the values of countries and second string which I entered when I'm searching for country. Now, I want all the results which contains "In" like result will be
India, Indonesia

as I have search for IN

// s1="In", s2="countries value"

  1. const s2 = "India, Australia,Canada,Luxembourg,Singapore,Switzerland,United States of America, Indonesia";
  2. const s1 = "In"
  3. const findString = (s1, s2) => {
  4. if(s2.includes(s1.charAt(0).toUpperCase() + s1.slice(1))){
  5. return s1;
  6. } else {
  7. return null;
  8. }

}

this function returning me "IN" but I want "India, Indonesia" as result

答案1

得分: 1

  1. const s2 = "India, Australia, Canada, Luxembourg, Singapore, Switzerland, United States of America, Indonesia";
  2. const s2Arr = s2.replace(/, +/g, ',').split(',') // create array all country
  3. function findString(keyword) {
  4. keyword = keyword.toLowerCase()
  5. return s2Arr.filter(item => item.toLowerCase().includes(keyword))
  6. }
英文:
  1. const s2 = "India, Australia,Canada,Luxembourg,Singapore,Switzerland,United States of America, Indonesia";
  2. const s2Arr = s2.replace(/, +/g, ',').split(',') // create array all country
  3. function findString(keyword) {
  4. keyword = keyword.toLowerCase()
  5. return s2Arr.filter(item => item.toLowerCase().includes(keyword))
  6. }

答案2

得分: 0

尝试如下:

  1. const s2 = "印度,澳大利亚,加拿大,卢森堡,新加坡,瑞士,美利坚合众国,印度尼西亚";
  2. const s1 = "印度";
  3. const findString = (s1, s2) => s2.split(',').filter((s) => s.indexOf(s1) === 0);
英文:

Try like this:

  1. const s2 = "India, Australia,Canada,Luxembourg,Singapore,Switzerland,United States of America, Indonesia";
  2. const s1 = "In"
  3. const findString = (s1, s2) => s2.split(',').filter((s) => s.indexOf(s1) === 0);

huangapple
  • 本文由 发表于 2023年2月6日 16:06:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定