Careless Careless - 7 months ago 14
Javascript Question

Select word next to symbol

I have jquery code on keypress 35 which is # to dropdown div. I need to get the word that is standing next to # e.g.

<textarea></textarea>
And I type #Michael I want to store #Michael in
var name

After making an ajax request to check if Michael exists in the database and if it does, echo it inside dropdown
div
. After what I click on some from the list and replace it with name and # before name like if I got result:

Michael Parker and click on this one to replace this one with name value.

I need to select word that is typed with #

[Q] how to select the word that is standing next to #?

Answer

Try this:

function getName(){
  var t = document.getElementsByTagName('textarea')[0].value;
  var name = t.split(' ');
  name.forEach(function(str){
    if(str[0] === '#') {
     return str;
    }
  });
}

I used this for test

<textarea>asjdaksdjans #hacj asdasd</textarea>
<button onclick="getName()">find</button>

I hope this is what you wanted.

EDIT

function getName(){
  var t = document.getElementsByTagName('textarea')[0].value;
  if(t[t.length-1]=== ' '){
    var name = t.split(' ');
    name.forEach(function(str){
       if(str[0] === '#') {
       console.log(str);
       }
    });
  }
}

For test:

<textarea onkeyup="getName()">asjdaksdjans #hacj asdasd</textarea>

EDIT

jQuery(function($){
 $('textarea').on('keyup', function(event){
   var text = $(this).val();
   if(text[text.length-1]=== ' ') {
     var name = text.split(' ');
     $.each(name, function(i, str) {
       console.log(i, str);
       if(str[0] === "#") {
         alert('name is:' +str);
       }
     });
   }
 });
});
Comments