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

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)!

Related

check if word already exists in the array [duplicate]

This question already has answers here:
Check if string inside an array javascript
(2 answers)
Closed 5 years ago.
I'm trying to check if the inputted word is already inside of my array. SO for example, if someone enters 'cat' more than once an error message will display saying "cat has already been entered". I've tried a few different combinations of code but nothing I do seems to work. The findword function is what I have so far. Can someone take a look at my code and explain why its not working and provide a possible fix.
On another note, why doesn't the "word: empty" message pop up when the input field has been left blank?.
<body>
<input type="text" id=input></input>
<button onclick="addword()" class="button" type = "button">Add word</button><br><br>
<button onclick="start()" class="button" type = "button">Process word</button><br><br>
<p id="ErrorOutput"></p>
<p id="output"></p>
<p id="nameExists"></p>
</body>
.
var array = [];
return = document.getElementById("input").value;
function start() {
var word = "word List";
var i = array.length
if (word.trim() === "") {
word = "word: Empty"
}
document.getElementById('ErrorOutput').innerHTML = word
while (i--) {
document.getElementById('output').innerHTML = array[i] + "<br/>" + document.getElementById('output').innerHTML;
}
var longestWord = {
longword: '',len: 0};
array.forEach(w => {
if (longestWord.len < w.length) {
longestWord.text = w;
longestWord.len = w.length;
}
});
document.getElementById('ErrorOutput').innerHTML = "The longest name in the array is " + longestWord.len + " characters";
}
function addword() {
return = document.getElementById('input').value;
array.push(return);
}
function findword() {
var nameExists = array.indexOf(
return) < 0 ?
'The number ' +
return +' does not exist in the array': 'The number ' +
return +' exists in the array'
document.getElementById('nameExists').textContent = nameExists
}
You can use array.indexOf(word) (command for your situation) to find the position of the word.
If the position is -1 the word is not inside the array.
More information on W3

replace symbol-number to gif

I need your help.
Here I have text: hello #005 goodbye.
How to make js replace text starting with # by img like <img src=/img/005.gif> if number (005<120)? I must have something like hello <img src=/img/005.gif> goodbye
In two steps to show process
var str = "hello #005 goodbye",
num = str.match(/\#(\d+) /)[1],
gif = '<img src="/img/'+num+'.gif" />';
console.log(str.replace("#"+num,gif));
One step - test for 3 digits too
var str = "hello #005 goodbye"
.replace(/\#(\d{3})/,'<img src="/img/$1.gif" />');
console.log(str);
With test:
function addGif(str) {
var num = str.match(/\#(\d+)/),
gif = num &&
num.length > 0 &&
parseInt(num[1]) >= 5 &&
parseInt(num[1]) <= 120 ? '<img src="/img/' + num[1] + '.gif" />' : "";
return gif ? str.replace("#" + num[1], gif) : "no number or number not in range";
}
var str = "hello # goodbye"; // will not return a match
console.log(addGif(str))
str = "hello #" // will not return a match
console.log(addGif(str))
str = "hello #005" // will return a match
console.log(addGif(str))
str = "hello #1005" // will not return a match
console.log(addGif(str))
str = "hello #100" // will return a match
console.log(addGif(str))
str = "hello #1111111111 goodbye" // will not return a match
console.log(addGif(str))
Makes no sense to do it in two steps when you can do it in one. The capture group in replace is $1 so you put that where you want the number to go.
var str = "hello #005 goodbye",
result = str.replace(/#(\d+)/,'<img src="/img/$1.gif" />');
console.log(result);
With a check inside the replace with the number requirement I missed the 2 times I read the question!
var str = "hello #005 goodbye",
result = str.replace(/#(\d{3})/, function (x, group1) {
var num = parseInt(group1);
return num >= 5 && num<=120 ? '<img src="/img/' + group1 + '.gif" />' : group1;
});
console.log(result);

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 ";
}
}
}

Hitting a word then highlight

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);
});
});​

Javascript String issue

i am trying to concat a query value into a link
wwww.test/video (query value) ".flv"
altought i think i did something wrong.
function doSomething() {
var test = new StringBuilderEx();
var a = querySt("number");
test.append("<h1>test</h1> ");
test.append("<a ");
test.append("href=\"http://test.com/video\"" + a + ".flv\" ");
test.append("Style =\"display:block;width:425px;height:300px;\" ");
test.append("id=\"player\" ");
test.append("</a> ");
test.append("<script language=\"JavaScript\" ");
test.append("> ");
test.append("flowplayer(\"player\" ");
test.append(", \"flowplayer-3.2.2.swf\" ");
test.append("); <\/script>");
return test.toString()
}
at the end all i get is a link with test.com/video and the the passed value. The StringBuilderEx is a JS script and queryST is
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i = 0; i < gy.length; i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
So it would be awesome if i get to know what am i not getting
where 1 is the query number.
href="http://test.com/video1.flv"
test.append("href=\"http://test.com/video\"" + a + ".flv\" ");
You have an extraneous \" there.
test.append("href=\"http://test.com/video" + a + ".flv\" ");
Also a missing >
test.append("id=\"player\" ");
should be
test.append("id=\"player\">");
Also, your link has no content to click on
test.append("</a> ");
should be
test.append("Click me!</a> ");

Categories