How to detect characters and words between these characters in a textbox with javascript?

I'm starting in javascript and I have a problem. Let's say I have the following text with the characters @, . and : in a textbox, for example:

In javascript I would like to recognize those characters and print in console the words that are after each character and before the other character, for example:

green is after @ , car-blue is after . , computer is after :

How can I do this?

2 answers

  • answered 2020-06-27 03:51 sonEtLumiere

    I hope this helps. split method supports regular expressions.

    var str = '';
    var signs = str.split(/[^@.:]+/g);
    var words = str.split(/[@.:]+/g);

  • answered 2020-06-27 03:55 Nick

    You could use Regexp.Exec to find all matching occurrences of a string of characters between two of your split characters:

    const inp = document.getElementById('input');
    let txt = inp.value;
    const regex = /([@.:])([^@.:]+)(?=[@.:]|$)/g;
    while ((m = regex.exec(txt)) !== null) {
      console.log(`${m[2]} is after ${m[1]}`);
    <textarea id="input"></textarea>