Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1767 How do you check to see if a string is contained within a list of strings?

You are here: irt.org | FAQ | JavaScript | Text | Q1767 [ previous next ]

Basic inList() function to check if the string 'testString' is in the list 'mainList'.

<html>

<head>
<title>JS List Find</title>
</head>

<script language="JavaScript1.2">
//Basic inList fn to check if the string 'testString' is in the list 'mainList'.

// mainList = List of strings eg 'aaa|bbbz|ggg|jio' OR 'aaa,bbbz,ggg,jio' OR 'aaa bbbz ggg jio'
// testString = input string to test for in above list eg 'AAA'
// delim = list delimeter, best to use '|'. If a sentence use ' '. If a list use ','
// CaseSens= Case Sensitive search. Val=true or false. When true, 'aaa' NOT= 'AAA'

// Please note that spaces (' ') at the beginning, or end, of a string are treated as part of
// the string, unless you are searching a sentence, in which case ' ' will become your delimiter.

function inList(mainList,testString,delim,caseSens) {
  if (caseSens == false) {
    mainList=mainList.toUpperCase();
    testString=testString.toUpperCase();
  }

  list_ToArray=mainList.split(delim); //turn mainList into an array
  var stringFound = false; // set var to default false when no match found
	
  for (i=0; i < list_ToArray.length; i++) {
    if (list_ToArray[i] == testString) {
      var stringFound = true; // if above 'if' statement=true, then match found.
      break; // break loop
    }
  }
  return stringFound; // if match found stringfound = true, else false will be returned.
}
</script>

<body onload="document.FName.inpString.focus();">

<form
  name="FName"
  action="inList.htm"
  onsubmit="alert('string in list = '+inList(document.FName.inpListString.value,document.FName.inpString.value,'|',false));">

  <!--- list to compare against --->

  <input name="inpListString" type="hidden" value="AAA |AAB | AAX|abc|Asd| deF| pRG|$%^*() ">

  <!--- input string to compare against above list --->

  <input name="inpString" type="text" value="AAA ">
  <input type="Submit" name="Go" value="Send">
</form>

</body>

</html>

Submitted by RSS

©2018 Martin Webb