How to take two strings and show the common characters?

Hey guys. Little help?

I’m trying to take two strings and show the common characters for each string.
Is this right?

How do I show the resulting string on my HTML?

HTML Code:
<form>
          <label for="string1">String 1</label>
          <input type="text" name="string-1" id="string1" placeholder="Input String 1" required>
                        
          <label for="string2">String 2</label>
          <input type="text" name="string-2" id="string2" placeholder="Input String 2" required>
                        
          <button type="submit" onclick="returnSubsequence()">Submit</button>
</form>
<p id="result"></p>
JS Code:

let returnSubsequence = () =>{
    let string1 = document.getElemenbtbyID("string1").value;
    let string2 = document.getElementbyID("string2").value;
    let resultstring = ' ';
    for (let i of string1){
        for(let n of string2){
            if( n === i){
                resultstring.push(n);
            }
        }
    };
    return resultstring;
}

Where do you want to show it?

Good point. I added a p element with an ID.

Now I’m confused on how to show the string inside the p element. If I’m not mistaken, I should use innerHTML, right?
But:

  1. The string is stored inside a variable, can I use it directly in innerHTML?
  2. If yes, I still won’t be able to add the element.innerHTML after the return statement, right?

What am I missing?

you need an event listener if youre using input and button

document.querySelector('button').addEventListener('click', returnSubsequence)

function returnSubsequence(){
    // your logic
    // ...
    console.log(result);
    
   // add <output> to html
    document.querySelector('output').innerHTML = result
}

Thanks guys. :slight_smile: