Hitting a word then highlight - javascript

I have tried in hours to make this work.
I need to have a function which highlights the char if it's correct.
Ex, word is "halluluja" and i have a input field.
When user hitting "h" it has to make "h" red in "halleluja", if user hit "ha" after, it has to highlight the a. and so on.
I have tried something with substr, without any luck.
'typing':function(e){
var c = w.length; //The word length, ex. halleluja
for ( i=0;i<e.length;i++){ //foreach each
var o = e.substr(0, e.length); var l = w.substr(i,i+1); //my typing substr, and the char substr
if ( o.toLowerCase() == l.toLowerCase()){ //correct
//highlight the letter.
}
}
},
The word container is here which outputs the word in that container.
document.getElementById('wordContainer').innerHTML = w;

Try this: http://jsfiddle.net/tqHRA/
html:
<div id="preview">hello world</div>
<input type='text' id='txt' />​
JavaScript:
var source = 'hello world';
$(document).ready(function(){
$('#txt').keyup(function(){
var text = $(this).val();
var replaced = source.replace(text, '<span class="highlight">' + text + '</span>');
$('#preview').html(replaced);
});
});​

Related

Find the word after specific word

i am new in javascript.
I have below code where textarea contains text as...
<textarea id="myBox" >
{Picker:} Helper
This is just demo...
</textarea>
<br/>
<span id="ans"></span> <br/>
<input type="button" onclick="getWord()" value="Click"/>
i am trying to find out the word exact after the {Picker:}, i.e. i want to find word "Helper". So word {Picker:} is the point from where i am starting to find immediate word after it. For this i using indexOf. What i did uptil now is ...
<script>
function getWord() {
var val = $("#myBox").val();
var myString = val.substr((val.indexOf("{Picker:}")) + parseInt(10), parseInt(val.indexOf(' ')) );
$("#ans").text(myString);
}
</script>
will anyone guide me to find what mistake i am making. Thanks in advance.
You should start from the index of "{Picker:}" + 9, because the length of the particular string is 9.
Parse till the the index of '\n' which is the line break character.
String.prototype.substr() is deprecated, use String.prototype.substring() instead.
function getWord() {
var val = $("#myBox").val();
var myString = val.substring((val.indexOf("{Picker:}")) + 9, val.indexOf('\n'));
$("#ans").text(myString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<textarea id="myBox">
{Picker:} Helper
This is just demo...
</textarea>
<br />
<span id="ans"></span> <br />
<input type="button" onclick="getWord()" value="Click" />
var val = $("#myBox").val();
console.log(val)
var tempArray = val.replace("\n", " ").split(" ");
var wordToFind;
for(var i = 0 ; i < tempArray.length; i++) {
var word = tempArray[i];
if (word == "{Picker:}") {
wordToFind = tempArray[i + 1]
}
}
console.log(wordToFind)
This will assign what ever word comes after Picker: to the wordToFind variable.
Check working :https://jsfiddle.net/o5qasnd0/14/
You could do something like this
const text = "{Picker:} Helper";
const wordArr = text.split(' ');
const idx = wordArr.indexOf('{Picker:}');
console.log(idx != -1 && (idx + 1) < wordArr.length ? wordArr[idx + 1] : 'not found');

Find lines in an element and then wrap it with <span> tags

I need to write a code where I split the html by br, find lines that start with a number and then add in span tags.
jQuery(document).ready(function($) {
var brExp = /<br\s*\/?>/i;
var swn = /^[0-9]+[^)]/;
var lines = $('.caption').html().split(brExp).filter(line => swn.test(line.trim()));;
jQuery.each(lines, function() {
console.log(this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="caption">
BBQ Porked Rolls.
Ingredients:
3 to 4 pounds pork shoulder<br />
1 tablespoon salt<br />
2 tablespoons brown sugar<br />
STEPS:
In the oven,...
<div>
I’ve already gotten the lines and all that’s left is to add in span tags around those lines without the need to create a new div for the result. Maybe by using replace(), wrap() or something else entirely. This is where I need help.
EXPECTED OUTPUT:
<span itemprop="recipeIngredient">3 to 4 pounds pork shoulder</span><br>
<span itemprop="recipeIngredient">1 tablespoon salt</span><br>
<span itemprop="recipeIngredient">2 tablespoons brown sugar</span><br>
Thanks
You just need to map() over the collection.
jQuery(document).ready(function($) {
var brExp = /<br\s*\/?>/i;
var swn = /^\d/;
var lines = $('.caption').html().split(brExp).map(function (line) {
// strip the whitespace
line = line.trim();
// check for number
if ( swn.test(line) ) {
// add enclosing span
line = '<span itemprop="recipeIngredient">' + line + '</span>';
}
// return the line for the new collection
return line;
}).join('<br />');
$('.caption').html(lines);
});
If you only want to change the first line, you can make the following minor change to the code:
jQuery(document).ready(function($) {
var firstOnly = true; // will check for number when this value is true
var brExp = /<br\s*\/?>/i;
var swn = /^\d/;
var lines = $('.caption').html().split(brExp).map(function (line) {
// strip the whitespace
line = line.trim();
// check 'firstOnly' is true before checking for number
if ( firstOnly && swn.test(line) ) {
// add enclosing span
line = '<span itemprop="recipeIngredient">' + line + '</span>';
// first matching line has been modified
// so set 'firstOnly' to false
firstOnly = false;
}
// return the line for the new collection
return line;
}).join('<br />');
$('.caption').html(lines);
});
Another approach could be using .replace() as you said.
jQuery(document).ready(function($)
{
var text = $(".caption").html();
var newText = text.replace( /(\d+.+)(<br)/g, '<span itemprop="recipeIngredient">$1</span>$2');
console.log(newText);
$(".caption").html(text);
});
the regex must be fixed a little, but i think the approach is valid.
https://jsfiddle.net/g6yegh1f/
UPDATE
You can try this :
jQuery(document).ready(function($)
{
var html = '';
var brExp = /<br\s*\/?>/i;
var lines = $('.caption').html().split(brExp);
jQuery.each(lines, function(index, value) {
html += '<span>' + value + '</span></br>';
});
$('.caption').html(html);
});
Use this link which has the number check and then appending the data to span taghttps://codepen.io/anon/pen/ZoaXYR?editors=1010
var data = `3 to 4 pounds pork shoulder<br />1 tablespoon salt<br />2 tablespoons brown sugar<br />`;
var brExp = /<br\s*\/?>/i;
var swn = /^\d/;
var lines = data.split(brExp).filter(line => swn.test(line.trim()));
$.each(lines, function() {
var ff = Number(this[0]);
alert(typeof(ff));
if(typeof(ff) == "number") {
alert("success");
$("#first").append("<span id='test'>" +this+"</span>");
}
});
I would probably do this:
jQuery(document).ready(function($) {
var brExp = /<br\s*\/?>/i;
var swn = /^\d/;
var lines = $('.caption').html().split(brExp)
//create span
lines= lines.map( line =>$('<span />').prop('itemprop','recipeIngredient').html(line))//.join('<br />');
//empty the div
$('.caption').empty();
jQuery.each(lines, function() {
$('.caption').append(this);
$('.caption').append('<br />');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="caption">
3 to 4 pounds pork shoulder<br />
1 tablespoon salt<br />
2 tablespoons brown sugar<br />
<div>
You can use the index to find the value that corresponds to the 0 key, check if it is a number and then use append/before methods to bind the same.

How to find if there is a space in a string... tricky

I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}

Reading textbox input and putting in one of two boxes javascript

I am trying to allow the user to enter 1 letter in a text box, and then the letters gets put into 1 of 2 boxes. This is for a hangman game, so it is going to divide the letters based on whether or not it is in the word. Here's my code. Hopefully someone can help me. I'm new to javascript! I've done a ton of googling, but to little avail.
var words = ['dog', 'computer', 'cat', 'monkey', 'human'];
var wordForGuess = chooseWord();
var wordLength = wordForGuess.length;
function chooseWord () {
return words[Math.floor(Math.random() * words.length)];
}
function writeWord()
{
var textarea = document.getElementById('textBox').value;
for (var x = 0; x<wordLength; x++)
{
if (textarea === wordForGuess.indexOf(x))
{
document.getElementById('correctLetters').value = textarea;
}
else
{
document.getElementById('incorrectLetters').value = textarea;
}
}
}
As well as the HTML for my textbox
<div id = 'letterInput'>
</div>
<input type = 'text' id = 'textBox' onkeyUp="writeWord()"/>
<div id = 'correctLetters'>
</div>
<div id = 'incorrectLetters'>
</div>
I think you have a few mistakes, including iterating over your characters in your chosen word and using the index of that iteration instead of just checking the value from the input box. I also think you should reset the value on each keyup. I also moved your onkeyup event out of the HTML into JavaScript, I think maybe in your case the JavaScript hadn't loaded yet but it's hard to tell from your example.
<div id = 'letterInput'>
</div>
<input type = 'text' id = 'textBox' />
<br/>
Correct:
<div id = 'correctLetters'>
</div>
<br/>
Incorrect
<div id = 'incorrectLetters'>
</div>
Here's the JavaScript with some fixes:
var words = ['dog', 'computer', 'cat', 'monkey', 'human'];
var wordForGuess = chooseWord();
var wordLength = wordForGuess.length;
function chooseWord () {
return words[Math.floor(Math.random() * words.length)];
}
function writeWord() {
var input, textarea;
input = document.getElementById('textBox')
textarea = input.value;
input.value = "";
console.log("writing word", textarea);
if (wordForGuess.indexOf(textarea) !== -1) {
document.getElementById('correctLetters').innerText += textarea;
} else {
document.getElementById('incorrectLetters').innerText += textarea;
}
}
document.getElementById("textBox").onkeyup = writeWord;
Here's a jsfiddle with this code.

how to get selected text surrounding context in javascript in different paragraph?

hi I have a few problems:
What might I get the word around the word selected, if the word before and after the selected word given limits only 20 words that surround the selected word?
how to get the correct position if the word in a paragraph have the same word, for example I have a sentence like this: foo laa foo doo then I choose the word "foo" whose position is in between the words laa and doo?
how to get word from a different paragraph?
for example:
p1 : I like the red shirt
p2: my mother did not like the red shirt
the word I selected is "mother", and I have to take 10 words around the word "mother" that is "I like the red dress" and "I do not like the red shirt."
notes:
question No. 2 is able to use the nextSibling and previousSibling?
this is my code i try :
<html>
<head>
<script type="text/javascript">
function getElements(){
var x = document.getElementsByTagName("body");
x = x[0].innerHTML;
x = x.replace(/&(lt|gt);/g, function (strMatch, p1){
return (p1 == "lt")? "<" : ">";});
var str = x.replace(/<\/?[^>]+(>|$)/g, "");
var emailPattern = /[_a-zA-Z0-9\.]+#[\.a-zA-Z0-9]+\.[a-zA-Z]+/gi;
var urlPattern = /[a-z]+:\/\/[^\s]+/gi;
var numberOrSymbolPattern = /[0-9\.,!##\$%\^\&*\(\)`~_\-=\+|\\{}\[\]\s:;<>\?\/]+/gi;
//////alert(str);
var str = str.replace(emailPattern , " ");
var str = str.replace(urlPattern , " ");
var str = str.replace(numberOrSymbolPattern , " ");
//////alert(str);
var str = str.replace(/[\n\f\r\t]/g, " ");
var hilangtandabaca = str.replace(/[.!:;'",?]/g," ");
var kataptg = hilangtandabaca;
//alert(kataptg);
var kata = new Array();
kata[0] = " is ";
kata[1] = " the ";
kata[3] = " of ";
kata[4] = " a ";
kata[5] = " or ";
kata[6] = " for ";
kata[7] = " from ";
kata[8] = " in ";
kata[9] = " this ";
kata[10] = " and ";
kata[11] = " on ";
kata[12] = " with ";
kata[13] = " my ";
for(var i=0,regex; i<kata.length; i++){
var regex = new RegExp(kata[i],"gi");
kataptg = kataptg.replace(regex," ");
}
var select = getSelected()+ "";
alert(select);
var index = kataptg.indexOf(select);
//alert("indeks select text:" + index);
if (index >= 0) {
var strBefore = "";
var strAfter = "";
//var strOri ="";
//if (index = -1)
//strOri = kataptg.substr(index);
//alert(strOri);
if (index > 0)
strBefore = kataptg.substr(0, index);
//alert(strBefore);
if (index < kataptg.length - 1)
strAfter = kataptg.substr(index + select.length, kataptg.length - (index + select.length));
//alert(strAfter);
alert("Before: " + strBefore + "\nAfter: " + strAfter);
}
}
function getSelected() {
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
} else if (document.selection) {
userSelection = document.selection.createRange();
}
return userSelection;
}
</script>
</head>
<body>
<h2>About</h2>
<p> my email : a#a.a
<p> my url http://id.wikipedia.org/wiki/URL
<p> my telepon number = 081330782
<p>okey In agriculture, the harvest is the process of gathering mature crops from the fields. Reaping is the cutting of grain or pulse for harvest, typically using a scythe, sickle, or reaper.[1] The harvest marks the end of the growing season, or the growing cycle for a particular crop, and this is the focus of seasonal celebrations of on many religions. On smaller farms with minimal mechanization, harvesting is the most labor-intensive activity of the growing season great yeah. !:;'",?</p>
<p>
<input type="button" onclick="getElements()" value="ambil select text" />
</p>
</body>
</html>
This is a perfect example of JavaScript's innerHTML and split() methods. You can loop through the content of all of the p elements. Here's an example of searching in the first paragraph:
contentArray = document.getElementByTagName('p')[0].innerHTML.split(' ')
split(' ') splits the content of the element into an array, separating by the spaces. innerHTML is self explanatory.
Now, to find your words. indexOf() is your friend in this case:
foodex = contentArray.indexOf('foo');
alert('The first occurrence of the string \'foo\' in the text is at word number ' + foodex);
Finally, to get surrounding words, just play with the array (this won't work if the occurrence of the string is close to the start or end of the paragraph, namely less than 10 words away:
alert('I am the 10th word after \'foo\'' + contentArray[foodex + 10 - 1]);
Good luck (no guarantees this code works out of the box)!

Categories