In Javascript / jQuery, how to check a specific part of a string and determine if it is a space or a letter?

I want to write a function where, when I click anywhere in a line (or sentence) in HTML, it will tell me if it is a letter or a space. Is it possible? For example, I click on any place inside this sentence:

<div id='sentence'>The cat in the hat.</div>

Let's say I click on the letter "a" inside "cat". I want him to warn me that I clicked on the character. Say I press spaces between "cat" and "in". I want him to return a warning that I pressed the space bar.

This may seem impossible, but I have one idea: you can click somewhere and check to the left and right of where you clicked (for example, you clicked right between the space and the letter), and if at least one of the characters is space (say left), it should return that you clicked on the space ... would it be easier to implement? I just need some advice.

+3
source share
3 answers

Working example @ http://jsfiddle.net/Kai/k4YMS/

function clickify (e) {
    var arr = e.innerText.split("") || e.textContent.split(""),
        max = arr.length,
        i = 0,
        template = "<span onclick='alert(this.innerText || this.textContent);'>$c</span>",
        result = "";

    for (; i < max; i += 1) {
        result += template.replace("$c", arr[i]);
    }

    e.innerHTML = result;   
}
+3
source

Directly, but if you take each character in the html elements, this will become possible. Here is what I thought:

var $sentence = $("#sentence");
var sentence = $sentence.html();

//we'll use this after we recreate the sentence
function tellMeWhatIAm(){
  //as its name says it tells what it is
  alert($(this).text());
}

$.each(sentence,function(i,t){
  //clear the sentence
  if(i==0) $sentence.html("");
  //create every char again
  //and bind click event to our function above
  var $span = $("<span/>",{"text" : t, "click" : tellMeWhatIAm});
  //append the chars back to the sentence wrapper
  $sentence.append($span);
});

Not tested, but the idea is quite simple.

Hope this helps, Sinan.

+1
source

Range, html.

  $('#sentence').click(function(e) {
    if (window.getSelection) {
      var cursor = window.getSelection().getRangeAt(0).startOffset 
      var str = e.target.innerHTML;
      alert(str[cursor]);

    } else {
      var range = document.selection.createRange();
      range.expand('character');
      alert(range.text);

    }

  });
+1

Source: https://habr.com/ru/post/1782649/


All Articles