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

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

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

const s2 = "India, Australia,Canada,Luxembourg,Singapore,Switzerland,United States of America, Indonesia";
const s1 = "In";

const findString = (s1, s2) => {
  if(s2.includes(s1.charAt(0).toUpperCase() + s1.slice(1))){
    return s1;
  } else {
    return null;
  }
}

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"

const s2 = "India, Australia,Canada,Luxembourg,Singapore,Switzerland,United States of America, Indonesia";
const s1 = "In"

const findString = (s1, s2) => {
if(s2.includes(s1.charAt(0).toUpperCase() + s1.slice(1))){
  return s1;
} else {
  return null;
}

}

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

答案1

得分: 1

const s2 = "India, Australia, Canada, Luxembourg, Singapore, Switzerland, United States of America, Indonesia";
const s2Arr = s2.replace(/, +/g, ',').split(',') // create array all country

function findString(keyword) {
  keyword = keyword.toLowerCase()

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

function findString(keyword) {
  keyword = keyword.toLowerCase()

  return s2Arr.filter(item => item.toLowerCase().includes(keyword))
}

答案2

得分: 0

尝试如下:

const s2 = "印度,澳大利亚,加拿大,卢森堡,新加坡,瑞士,美利坚合众国,印度尼西亚";
const s1 = "印度";

const findString = (s1, s2) => s2.split(',').filter((s) => s.indexOf(s1) === 0);
英文:

Try like this:

const s2 = "India, Australia,Canada,Luxembourg,Singapore,Switzerland,United States of America, Indonesia";
const s1 = "In"

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:

确定