Home > OS >  Highlight the word in array
Highlight the word in array

Time:02-27

I have 2 issues:

  1. Array split functionality as I cannot use it not sure why?
  2. Words are not highlighting.

const text = [
        `Jelly sweet roll jelly beans biscuit pie macaroon chocolate donut. Carrot cake caramels pie sweet apple pie tiramisu carrot cake. Marzipan marshmallow croissant`  
    ]; // this is what i want to use instead of 'p' but also below not working
    function selectWord() {
        //const p = document.querySelector('p');
        text.innerHTML = text.innerText
            .split('')
            .map((word) =>
                word.length > 5 ? `<span >${word}</span>` : word
            )
            .join('');
    }
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .lightext {
            background-color: yellow;
        }
    </style>
</head>

<body>
    <p>This is the extremely long paragraph that we want to highlight all words longer than eight characters in.</p>
</body>
<script src="app1.js"></script>

</html>

CodePudding user response:

So, there are a few issues. I assume you changed the code for testing because you're not calling the function selectWord() anywhere (and the element is commented out).

You cannot use .split('') because that breaks strings into individual characters, not words, so everything has a length of 1. You need to change both your split and join to be .split(' ') and .join(' ').

Please also note, your text variable is an array, not a DOM object. Therefore it does not posses the innerHTML and innerText properties

The correct script would be.

function selectWord(str) {
  const el = document.querySelector("p")
  const highlightedText = str.split(' ').map((word) => word.length > 5 ? `<span >${word}</span>` : word).join(' ')
  el.innerHTML = highlightedText
}

selectWord('this is a longer string than normal')

CodePudding user response:

I simply fixed the obvious bugs in your code. Most notably, splitting words on spaces (where you had an empty string) and then reassembling them by the same.

    function selectWord() {
        const p = document.querySelector('p');
        console.log(p.innerText.split(' '));
        p.innerHTML = p.innerText
            .split(' ')
            .map((word) =>
                word.length > 5 ? `<span >${word}</span>` : word
            )
            .join(' ');
    }
    selectWord();
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .lightext {
            background-color: yellow;
        }
    </style>
</head>

<body>
    <p>This is the extremely long paragraph that we want to highlight all words longer than eight characters in.</p>
</body>
<script src="app1.js"></script>

</html>

CodePudding user response:

  1. selectWord function was never called
  2. The text should not be an array but a string
  3. In split and in join, you should have a string with a space to break up the words. An empty string will split all characters

const text = `Jelly sweet roll jelly beans biscuit pie macaroon chocolate donut. Carrot cake caramels pie sweet apple pie tiramisu carrot cake. Marzipan marshmallow croissant`; // this is what i want to use instead of 'p' but also below not working
    function selectWord() {
        const p = document.querySelector('p');
        p.innerHTML = text
            .split(' ')
            .map((word) =>
                word.length > 5 ? `<span >${word}</span>` : word
            )
            .join(' ');
    }
    selectWord();
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .lightext {
            background-color: yellow;
        }
    </style>
</head>

<body>
    <p>This is the extremely long paragraph that we want to highlight all words longer than eight characters in.</p>
</body>
<script src="app1.js"></script>

</html>

CodePudding user response:

An alternative solution with fewer steps (no splitting, mapping, or joining) would be to use replace with a regular expression to identify words that have more than 5 letters, and then attach the result as HTML to the paragraph element.

const text = 'Jelly sweet roll jelly beans biscuit pie macaroon chocolate donut. Carrot cake caramels pie sweet apple pie tiramisu carrot cake. Marzipan marshmallow croissant';
const para = document.querySelector('p');

function highlightWords(text) {
  const regex = /[a-zA-Z]{6,}/g;
  return text.replace(regex, (word) => {
    return `<span >${word}</span>`;
  });
}

para.innerHTML = highlightWords(text);
.highlight { background-color: yellow; }
<p></p>

If you have an array of string you want to add to the page you can iterate over the array and add new paragraphs to the document body with insertAdjacentHTML.

const arr = [
  'Jelly sweet roll jelly beans biscuit pie macaroon chocolate donut. Carrot cake caramels pie sweet apple pie tiramisu carrot cake. Marzipan marshmallow croissant',
  'Moon gopher travel onomatopoeia volcano tree'
];

const { body } = document;

function highlightWords(text) {
  const regex = /[a-zA-Z]{6,}/g;
  return text.replace(regex, (word) => {
    return `<span >${word}</span>`;
  });
}

for (const text of arr) {
  const para = `<p>${highlightWords(text)}</p>`;
  body.insertAdjacentHTML('beforeend', para);
}
.highlight { background-color: yellow; }

  • Related