Categories
CSS HTML JavaScript

Building a Custom JavaScript Dictionary for Spelling and Grammar Checking on Your Staging Server

Building a custom dictionary in JavaScript can be an effective way to improve the quality and accuracy of your content. By including commonly misspelled words, industry-specific terminology, and other important words in your dictionary, you can ensure that your spell-checking software is correctly identifying errors and improving the quality of your writing.

In this article, we will walk through the steps to build a custom dictionary in JavaScript that highlights custom spelling and grammar errors on your staging server. We will also include the required HTML, CSS, and JavaScript code to build it.

Define the Custom Dictionary

The first step to building a custom dictionary is to define the words you want to include in your dictionary. You can start by creating an array of words that you want to include. For example:

const customDictionary = [
  "JavaScript",
  "web development",
  "industry-specific",
  "misspelled",
  "grammar",
  "Hunspell",
  "JSON",
  "library",
  "GrammarBot",
  "machine learning",
  "HTML",
  "content management system",
];

This is just a small sample of words that you may want to include in your custom dictionary. You should tailor your custom dictionary to your specific needs, including any industry-specific terminology that you use.

Build the HTML and CSS

Next, we need to build the HTML and CSS for the interface that the user will interact with to input text and see the results of the spelling and grammar checks.

We will use a simple form with a textarea for the user to input their text, and a button to initiate the checks. We will also create a container for the results to be displayed.

Here is the HTML code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Custom Dictionary Spell Checker</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="container">
      <h1>Custom Dictionary Spell Checker</h1>
      <form>
        <label for="inputText">Enter text:</label><br>
        <textarea id="inputText" name="inputText" rows="10" cols="50"></textarea><br>
        <button id="checkButton">Check Spelling and Grammar</button>
      </form>
      <div id="results"></div>
    </div>
    <script src="script.js"></script>
  </body>
</html>

And here is the CSS code:

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  text-align: center;
}

form {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 10px;
}

textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-sizing: border-box;
  resize: none;
}

button {
  display: block;
  margin: 20px 0;
  padding: 10px 20px;
  border: none;
  background-color: #4CAF50;
  color: #fff;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #3e8e41;
}

#results {
  display: none;
  margin-top: 20px;
  padding: 20px;
  border: 1px solid
}

Implement the JavaScript

Now that we have the HTML and CSS in place, it’s time to implement the JavaScript code that will check the spelling and grammar of the user’s input text using the custom dictionary we defined earlier.

First, we need to get references to the elements in our HTML that we will be using in our JavaScript code. We can use the querySelector method to get references to the textarea, button, and results container:

const inputText = document.querySelector('#inputText');
const checkButton = document.querySelector('#checkButton');
const results = document.querySelector('#results');

Next, we need to add an event listener to the button that will initiate the spelling and grammar checks when it is clicked. We can use the addEventListener method to do this:

checkButton.addEventListener('click', function(event) {
  event.preventDefault(); // prevent form submission

  const input = inputText.value; // get user input
  const errors = checkSpellingAndGrammar(input); // check spelling and grammar
  displayResults(errors); // display results
});

In this code, we are preventing the form from being submitted when the button is clicked, getting the user’s input from the textarea, checking the spelling and grammar using the checkSpellingAndGrammar function (which we will define next), and then displaying the results using the displayResults function (which we will also define next).

Now we need to define the checkSpellingAndGrammar function. This function will take the user’s input text and check it for spelling and grammar errors using the custom dictionary we defined earlier.

Here is the code for the checkSpellingAndGrammar function:

function checkSpellingAndGrammar(text) {
  const errors = [];

  // Split the input text into words
  const words = text.split(/\b/);

  // Check each word for spelling and grammar errors
  for (let i = 0; i < words.length; i++) {
    const word = words[i];

    // Check if the word is in the custom dictionary
    if (customDictionary.indexOf(word.toLowerCase()) === -1) {

      // Check if the word is misspelled
      const misspelled = spellcheck(word);
      if (misspelled) {
        errors.push({ word, type: 'misspelled' });
      }

      // Check if the word is grammatically incorrect
      const grammaticallyIncorrect = checkGrammar(word);
      if (grammaticallyIncorrect) {
        errors.push({ word, type: 'grammatically incorrect' });
      }
    }
  }

  return errors;
}

In this code, we first initialize an empty array called errors. We then split the user’s input text into an array of words using a regular expression. We then iterate over each word in the array, checking if it is in the custom dictionary. If it is not in the custom dictionary, we check if it is misspelled using the spellcheck function (which we will define next), and if it is grammatically incorrect using the checkGrammar function (which we will also define next).

If a word is either misspelled or grammatically incorrect, we add an object to the errors array containing the word and the type of error. Once we have checked all the words, we return the errors array.

Now we need to define the spellcheck and checkGrammar functions. These functions will use third-party libraries to check the spelling and grammar of the words.

For spelling checking, we will use a library called Hunspell.js, which is a JavaScript implementation of the Hunspell spellchecker. We will load

<script src="https://cdn.jsdelivr.net/npm/hunspell.js@3.3.0/hunspell.js"></script>

We can then define the spellcheck function using the Hunspell object from the Hunspell.js library:

function spellcheck(word) {
  const affData = new Uint8Array(customDictionaryAff);
  const dicData = new Uint8Array(customDictionaryDic);
  const hunspell = new Hunspell(affData, dicData);

  return !hunspell.spell(word);
}

In this code, we first convert the custom dictionary files to Uint8Array objects, which is the format expected by the Hunspell object. We then create a new Hunspell object using these data files.

We can then call the spell method on the Hunspell object to check if the word is spelled correctly. If the word is not spelled correctly, the spell method will return false, which we negate using the ! operator to return true.

For grammar checking, we will use a library called grammarbot-js, which is a JavaScript implementation of the GrammarBot API. We will load this library using a CDN link in our HTML file:

<script src="https://cdn.jsdelivr.net/npm/grammarbot-js@3.4.0/dist/grammarbot.min.js"></script>

We can then define the checkGrammar function using the GrammarBot object from the grammarbot-js library:

function checkGrammar(word) {
  const grammarbot = new GrammarBot({
    api_key: 'YOUR_API_KEY', // replace with your own API key
    language: 'en-US' // set the language to English
  });

  return new Promise((resolve, reject) => {
    grammarbot.check(word, (error, result) => {
      if (error) {
        reject(error);
      } else {
        resolve(result.matches.length > 0);
      }
    });
  });
}

In this code, we first create a new GrammarBot object using our API key and setting the language to English. We then return a new Promise that will resolve with a boolean value indicating whether the word is grammatically incorrect or not.

Inside the Promise, we call the check method on the GrammarBot object, passing in the word and a callback function that will be called with the results of the grammar check. If there is an error, we reject the Promise with the error message. Otherwise, we resolve the Promise with a boolean value indicating whether there are any grammar matches in the results.

Finally, we need to define the displayResults function. This function will take the errors array returned by the checkSpellingAndGrammar function and display the results in the results container on the HTML page.

function displayResults(errors) {
  if (errors.length > 0) {
    let html = '';
    for (let i = 0; i < errors.length; i++) {
      const error = errors[i];
      html += `<p><strong>${error.word}</strong> is ${error.type}</p>`;
    }
    results.innerHTML = html;
  } else {
    results.innerHTML = '<p>No spelling or grammar errors found.</p>';
  }
}

In this code, we first check if there are any errors in the errors array. If there are, we iterate over each error and create an HTML string to display the error message in the results container on the HTML page. If there are no errors, we display a message indicating that no errors were found.

Now that we have defined all of our functions, we can tie everything together in the checkText function. This function will take the text from the textarea element on the HTML page, split it into words, and check each word for spelling and grammar errors.

function checkText() {
  const text = textarea.value;
  const words = text.split(' ');

  const promises = [];

  for (let i = 0; i < words.length; i++) {
    const word = words[i].toLowerCase();
    if (word.length > 0) {
      const spellingPromise = spellcheck(word);
      const grammarPromise = checkGrammar(word);
      promises.push(Promise.all([spellingPromise, grammarPromise])
        .then(results => {
          const spellingResult = results[0];
          const grammarResult = results[1];

          if (spellingResult || grammarResult) {
            return { word, type: spellingResult ? 'misspelled' : 'grammatically incorrect' };
          }
        }));
    }
  }

  Promise.all(promises).then(errors => {
    errors = errors.filter(error => error);
    displayResults(errors);
  });
}

In this code, we first get the text from the textarea element on the HTML page and split it into an array of words. We then iterate over each word, converting it to lowercase and checking its spelling and grammar using the spellcheck and checkGrammar functions. We add the resulting promises to an array of promises.

Once we have checked all the words, we use Promise.all to wait for all the promises to resolve. We then filter out any undefined values from the errors array and call the displayResults function with the remaining errors.

We can now add event listeners to the HTML elements to call the checkText function when the user clicks the Check button or presses the Enter key in the textarea element:

button.addEventListener('click', checkText);

textarea.addEventListener('keydown', event => {
  if (event.keyCode === 13 && !event.shiftKey) {
    event.preventDefault();
    checkText();
  }
});

In this code, we add a click event listener to the button element that calls the checkText function when the user clicks the button. We also add a keydown event listener to the textarea element that calls the checkText function when the user presses the Enter key and does not hold down the Shift key.

Finally, we can style the HTML page using CSS to make it look more presentable:

body {
  font-family: Arial, sans-serif;
}

.container {
  width: 80%;
  margin: 0 auto;
}

h1 {
  text-align: center;
}

textarea {
  width: 100%;
  height: 200px;
  margin-bottom: 10px;
}

button {
  padding: 10px;
  border: none;
  background-color: #4CAF50;
  color: white;
  font-weight: bold;
  cursor: pointer;
}

button:hover {
  background-color: #3E8E41;
}

#results {
  margin-top: 20px;
}

#results p {
  margin: 0;
}

#results strong {
  color: red;
}

In this code, we set the font family to Arial, sans-serif for the entire page. We then set the width of the container div to 80% and center it using `margin: 0 auto

. We set the text alignment of the h1 element to center and add some margin to the bottom of the textarea element. We style the button element with a green background color and white text, and add a hover effect with a darker shade of green. Finally, we style the results div with some margin at the top, and color any misspelled words in red using the strong tag.

And that’s it! We have now created a custom JavaScript dictionary that can highlight custom spelling and grammar errors on our staging server. You can see the final code below:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Custom Dictionary Spellchecker</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .container {
      width: 80%;
      margin: 0 auto;
    }

    h1 {
      text-align: center;
    }

    textarea {
      width: 100%;
      height: 200px;
      margin-bottom: 10px;
    }

    button {
      padding: 10px;
      border: none;
      background-color: #4CAF50;
      color: white;
      font-weight: bold;
      cursor: pointer;
    }

    button:hover {
      background-color: #3E8E41;
    }

    #results {
      margin-top: 20px;
    }

    #results p {
      margin: 0;
    }

    #results strong { color: red;
}
 </style>
</head>
<body>
  <div class="container">
    <h1>Custom Dictionary Spellchecker</h1>
    <textarea id="text"></textarea>
    <button onclick="checkSpelling()">Check Spelling</button>
    <div id="results"></div>
  </div>
  <script>
    const dictionary = ["hello", "world", "javascript", "programming"]; // Our custom dictionary

    function checkSpelling() {
      const text = document.getElementById("text").value;
      const words = text.split(" ");
      let errors = [];

      words.forEach((word) => {
        if (!dictionary.includes(word.toLowerCase())) {
          errors.push(word);
        }
      });

      const resultsDiv = document.getElementById("results");

      if (errors.length > 0) {
        let message = "The following words are misspelled: ";
        errors.forEach((error) => {
          message += `<strong>${error}</strong> `;
        });
        resultsDiv.innerHTML = `<p>${message}</p>`;
      } else {
        resultsDiv.innerHTML = "<p>No misspelled words found!</p>";
      }
    }
  </script>
</body>
</html>

Now you can copy this code into a new HTML file and open it in your web browser to test it out. Try typing in some text with misspelled words and clicking the “Check Spelling” button to see the results.

Building a Custom JavaScript Dictionary for Spelling and Grammar Checking on Your Staging Server

In conclusion, building a custom JavaScript dictionary that highlights custom spelling and grammar errors on your staging server is a useful tool to have in your web development arsenal. With this simple implementation, you can help ensure that your website’s content is free from embarrassing typos and spelling mistakes.

By using the split() method to break up the input text into individual words and comparing each word against a predefined dictionary, we can quickly and easily identify any misspelled words. And by using the DOM manipulation functions in JavaScript, we can dynamically update the page to display the results.

With a little bit of HTML, CSS, and JavaScript knowledge, you can easily build your own custom dictionary spellchecker for your website. So why not give it a try and improve the quality of your website’s content today?