skip to Main Content

I want to target the first two words of a paragraph using javascript and change their size.

for example:

<p>My name is muhammad hamd</p>

Here I just want to target ‘My name’, the first two words of the p tag, and change their size.

2

Answers


  1. See comments inline:

    // First get a reference to the element
    const p = document.querySelector("p");
    
    // Then get the text content of the element
    let text = p.textContent;
    
    // Take that string and break it up (at the spaces) into an array
    //   Here the // denotes a regular expression
    //   the s is the JavaScript escape code for space
    //   the + indicates that it can be one or more spaces in a row
    //   the g at the end means look through the entire string
    let words = text.split(/s+/g);
    
    // Extract just the first two words
    console.log(words[0], words[1]);
    <p>My name is muhammad hamd</p>

    The steps can be combined for more concise code:

    // Extract just the first two words
    let words = document.querySelector("p").textContent.split(/s+/g)
    console.log(words[0], words[1]);
    <p>My name is muhammad hamd</p>
    Login or Signup to reply.
  2. Extract specific words from element

    You need to get the element p, get the string and use slice()-method to get what you want.

    
       // 1. Get element <p> as a variable
       const elementP = document.querySelector('p');
    
       // 2. Pick up the string content
       let content = elementP.textContent;
    
       // 3. Use split() method to create array of the words in <p>
       let words = content.split(' ');
    
       // 4. Take the first two elements from the array
       let firstTwo = words.slice(0, 2);
    
       // 5. Squash the first two words into a single string
       let result = firstTwo.join(' ');
    
       // 6. Show first two words in console log
       console.log(result);
    
       // Your example element
       <p>My name is muhammad hamd</p>
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search