auto capital correct in search bar with javascript issue

50 Views Asked by At

hey guys I have a search bar and want to make it so when a user searches it automatically corrects and searches,

eg- user types jane doe, it will correct to Jane Doe

this is a pain as I can't add 2 variants of the names as it doesnt work, so basically the user has to type the exact format that's in my javascript or the search will return no results

any help on this would be amazing

              <form action="" style="margin-bottom: 40px;">
                <div class="input-group">
                  <input type="search" id="search" autocomplete="off" onchange="openPage()"  class="form-control rounded-pill rounded-end-0 border-0 ps-4" placeholder="Search Celebrity Bones...">
                  <button type="button" id="button" onclick="openPage()" value="Chercher" class="btn btn-primary rounded-pill rounded-start-0 shadow-none">
                    <i class="fa fa-search"></i>
                  </button>
                </div>
              </form>     

and this is my javascript I know its not the best but im new to using search bars,

function openPage() {
            var x = document.getElementById("search").value;

            if (x === "Jane Doe") { // if they don't search the exact name it won't work
               window.open ("files/Janedow.html"); // this is the file
            }
}

if you look in my javascript I tried to add eg "Jane doe , Jane Doe", but it wouldn't work this would of been perfect because I could have made lots of keywords

2

There are 2 best solutions below

2
Rohad Bokhar On BEST ANSWER

You can try using Regex to replace the first letter of each word to a capital

var x = document.getElementById("search").value;
x = x.replace(/\b\w/g, (firstLetter) => firstLetter.toUpperCase());

if (x === "Jane Doe") { 
    window.open ("files/Janedow.html"); 
}

Note: This is only to correct the name from jane doe to Jane Doe


You can also use regex to check if the input from user contains Jane Doe (you can addi flag for case insensitive regex)

const regex = /jane doe/i; 
if (regex.test(x)) { 
    window.open ("files/Janedow.html"); 
}
0
arngrim280 On

try with a function like this

function search() {
  var input = document.getElementById("searchBar").value;
  var correctedInput = input.replace(/\w\S*/g, function(txt) { 
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });
  document.getElementById("searchBar").value = correctedInput;
 
}

This function capitalize the first letter of each word and with the 'toLowerCase' it converts the other letters to lowercase, just in case that user types the search words with uppercase