Highlight strings that matches regex using javascript - javascript

I'm trying to learn more JavaScript by working on projects I'm interested in so pardon me if this is a very basic question.
I'm trying to build a tool that detects a string of words (preferably a text or JSON file) from the HTML page (in a div).
<html>
<title>Hello world</title>
<head>
</head>
<body>
<div class="print" id="print"></div>
<textarea class="textarea" class="answerBox" id="answerBox"></textarea>
<script>
var inputBox = document.getElementById('answerBox');
inputBox.onkeyup = function(){
document.getElementById('print').innerHTML = inputBox.value;
}
</script>
</body>
</html>
Here's what I've done so far: https://jsfiddle.net/mc3kqj4t/ It's basically still nothing but what I want to do is to type in something in the box, then as soon as I type the text instantly appears on the page but also while that happens I can see if any of the words that I typed contain certain keywords that match a RegEx (for example "fox" and it's permutations "f ox" or something like that). I need to reference an external file because the words need to be updated every now and then.
Can anyone help?

Thoughts:
You can store the input text in a variable and regex in another. (not sure in your case whether both are necessary)
Use JavaScript replace to replace regex matches, with your highlighted HTML.
Please refer to this demo based on your code.
<html>
<title>Vulgarism Sandbox</title>
<head>
</head>
<body>
<p>Try input in the textarea with some text containing `a\w+`</p>
<div class="print" id="print"></div>
<textarea class="textarea" class="answerBox" id="answerBox" value="abcde"></textarea>
<input value="a\w+" id="regexInput" />
<script>
var inputBox = document.getElementById('answerBox');
inputBox.onkeyup = function() {
const regexInput = new RegExp(document.getElementById('regexInput').value, 'ig');
const text = document.getElementById('answerBox').value;
// replace regex matches in input text, and add 'highlight' HTML
const renderText = text.replace(regexInput, match => `<b>${match}</b>`)
document.getElementById('print').innerHTML = renderText;
}
</script>
</body>
</html>

Related

Javascript queries

I have been trying to practice some exercises using Javascript. Here are some challenges I have been facing. Please suggest if there is a mistake or something that I am missing.
Note: I do not want to use Jquery at this stage.
Exercise:
Ask the user to input some text. On the click of a button, the entered text needs to be displayed as rotating.
The first approach I took gets me the result the first time. But if I enter a new text, and click the button, the rotation fluctuates between the old text and new. I am not sure if I am explaining it right. Here's the first attempt:
Test the result: http://learningharvest.co.in/
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Enter the text to be reversed</p>
<div id="texttoberotated">
<input type="text" id="texttobeRot"></p>
</div>
<div>
<button id="rotateText">Rotate Text</button>
<p id="rotatedText"></p>
</div>
<script>
document.getElementById("rotateText").onclick=function (){
var text=null;
text= document.getElementById("texttobeRot").value;
var finaltext=text;
document.getElementById("rotatedText").innerHTML=finaltext;
setInterval(rotatetext, 500);
var numberofRotations=0;
var length=0;
length=text.length;
var i=0;
function rotatetext(){
i=length;
if(numberofRotations<=text.length){
getText();
}else{
numberofRotations=0;
length=text.length;
i=length;
preText=null;
postText=null;
finaltext=null;
getText();
}
}
function getText(){
preText=text.slice(length);
postText=text.slice(0,i);
i--;
finaltext=preText+" "+postText;
numberofRotations++;
length--;
document.getElementById("rotatedText").innerHTML=finaltext;
}
}
</script>
</body>
2. The second attempt I am making is using the childNodes method. However, I am unable to get the nodeValue of the input tag. The nodeValue is working if I try with any other element, but not with the input element.
Also, the function rotatetext is being executed on page load and not when the button is clicked. Works well if I add the onclick event inline in the button tag itself.
Here's the error i get in console:
Rotate text parent child method.html:27 Uncaught TypeError: Cannot read property 'nodeValue' of undefined
at rotatetext (Rotate text parent child method.html:27)
at Rotate text parent child method.html:23
Here's the body content I have drafted so far. At this stage, I am just trying to replace the text "Show Rotated Text here" with the text entered by the user.
<body>
<p>Enter the text to be reversed</p>
<input type="text" id="texttobeRot">
<button id="rotateText">Rotate Text</button>
<p id="rotatedText">Show Rotated Text here</p>
<script>
document.getElementById("rotateText").onclick= rotatetext();
function rotatetext(){
var element=document.getElementById("texttobeRot");
var textNode=element.childNodes[0];
var text=textNode.nodeValue;
var texttobeRotated;
texttobeRotated= text;
document.getElementById("rotatedText").innerHTML=texttobeRotated;
};
Look forward to all of your inputs.
Using the first approach if you add
document.getElementById("texttoberotated").onkeyup = function() {
text = '';
}
to the bottom of your script it will clear the text value when you begin to type and you can enter a new word without the issue of them being jumbled together as you described.
I put a working example of your code at https://codepen.io/chaosmaths/pen/LrwrpQ

Textarea automatic line break

I have a textarea on my site where I want to paste URLs.
Is this possible to create line break every time I paste URL? If not, can it create line break when I enter space?
I've searched for the solution but all i found is the solution to create line breaks after form submit which didn't help me.
Fiddle here: https://jsfiddle.net/3sj2644z/
this.value = this.value + "\n";
You listen for the paste event on the textarea and you grab the text that is currently in it and append a linebreak with the escape character \n to it and then place that new string value back into the textarea.
You don't use html in the textarea so the br tag doesn't work if you think so.
function ConvertToLinks() {
str = document.getElementById("S1").value;
str = str.replace(/\r\n|\n/g,'<br>');
document.getElementById('txtLinks').innerHTML = str;
}
<html>
<head>
<title>Text area redirect</title>
</head>
<body>
<textarea rows="5" id="S1" name="S1" cols="40">
Yahoo
Google
Web Developer
from Web
</textarea>
<br><button onclick="ConvertToLinks()">Convert to Links</button>
<div id="txtLinks" style="width:350px;min-height:100px;border:1px solid red"></div>
</body>
</html>
By http://www.codingforums.com/javascript-programming/195565-place-links-textarea.html

Change case to lowercase in JS text area

How do I change the case of a character in a textbox/textarea to lowercase onchange?
<html>
<head>
<title>Page Title</title>
<script>
function f2(string)
{
string=string.toUpperCase();
alert(string);
}
</script>
</head>
<body>
<p>Here are my text entry objects:</p>
<form>
<p>
Change the scripting (still using one function) so that the text from the alert is shown in uppercase from the textbox but lowercase from the textarea:<br>
<textarea onchange='f2(this.value);'></textarea>
</p>
</form>
</body>
Have you tried;
function f2(textarea)
{
string = textarea.value;
alert(string);
string = string.toLowerCase();
textarea.value = string;
}
With the modification to the onChange as;
<textarea onchange='f2(this);'></textarea>
Simply change the value and assign it back.
<textarea onchange='this.value=this.value.toLowerCase();'></textarea>
Because nobody fixed your code
HTML:
<p>Here are my text entry objects:</p>
<form>
<p>
Change the scripting (still using one function) so that the text from the alert is shown in uppercase from the textbox but lowercase from the textarea:<br>
<textarea></textarea>
</p>
JS:
document.getElementsByTagName("textarea")[0].addEventListener("change", function () {
this.value = this.value.toLowerCase();
});
You want to add a change event handler. Inside the event handler you merely overwrite the value property of the element with the string changed to lowerCase.
I also fixed your in-line javascript in your HTML. It is the devil, avoid it.
Live Example
Just use the .toLowerCase() method.
Use onchange='this.value = this.value.toUpperCase();' to make the text uppercase. Replace toUpperCase with toLowerCase for the opposite.
If desired, you can use your own function instead of just toUpperCase, passing either just the textarea's value or the entire textarea. For example (value only):
<!-- HTML -->
<textarea onchange='this.value = f2(this.value);'></textarea>
// JavaScript
function f2(oldText) {
var newText = oldText.toUpperCase();
return newText;
}
Or (entire textarea):
<!-- HTML -->
<textarea onchange='f3(this);'></textarea>
// JavaScript
function f3(ta) {
ta.value = ta.value.toUpperCase();
}
I would pass this and then work on it like a DOMNode:
<p>Here are my text entry objects:</p>
<form>
<p>
Change the scripting (still using one function) so that the text from the alert is shown in uppercase from the textbox but lowercase from the textarea:<br>
<textarea onchange='f2(this);'></textarea>
</p>
</form>
function f2(el) {
el.value = el.value.toLowerCase();
}
http://jsfiddle.net/HDR8t/1
Problem 1
I believe the onchange event only gets fired when the <textarea> no longer has focus. Instead, you'll want to use the onkeyup event.
Problem 2
You're only passing the string to the function. If you want to change the actual text in the <textarea>, you'll need to pass the actual DOM element to your function:
<textarea onkeyup="f3(this)"></textarea>
Problem 3
Once you pass the element into your function, you'll need to update its value attribute:
function f3(elem) {
elem.value = elem.value.toLowerCase();
}
Try the [.toLowerCase()][1] method.
<textarea onchange='this.value=this.value.toLowerCase();'></textarea>

Javascript text field live view

I am trying to make a similar bit of code like at the bottom of this page to leave a comment. I have the basic code but the output does not register new lines (or HTML, but that isn't important). I have the function below called on key-up on the text field. Any help would be greatly appreciated. Thanks
Here is the whole page (Now working)
<html>
<body>
<form>
<textarea id="text" onkeyup="outputText()"></textarea>
</form>
<div id="outputtext" style="width:500px;">
</div>
</body>
<script type="text/javascript">
function outputText()
{
var text = document.getElementById('text').innerHTML;
document.getElementById('outputtext').innerHTML = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2');
}
</script>
</html>
document.getElementById('outputtext').innerHTML = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br>$2')
Have you tried getting the textarea contents as
var text = document.getElementById('text').value; instead?
I think it's good for you to take a look at how tools like jQuery can make your live easier in this kind of cases. Your particular question is a bit unclear however...can you give us more details?
You can use the <pre> (preformatted) tag so that html and carriage returns are represented without doctoring the field input
html:
<input id="text" type="text" />
<pre id="outputtext"></pre>
jQuery:
$(document).ready(function () {
$('#text').keyup(function () {
$('#outputtext').html($(this).val());
});
});

jQuery .append() not appending to textarea after text edited

Take the following page:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"/>
</head>
<body>
<div class="hashtag">#one</div>
<div class="hashtag">#two</div>
<form accept-charset="UTF-8" action="/home/index" method="post">
<textarea id="text-box"/>
<input type="submit" value ="ok" id="go" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$(".hashtag").click(function() {
var txt = $.trim($(this).text());
$("#text-box").append(txt);
});
});
</script>
</body>
</html>
The behavior I would expect, and that I want to achieve is that when I click on one of the divs with class hashtag their content ("#one" and "#two" respectively) would be appended at the end of the text in textarea text-box.
This does happen when I click on the hash tags just after the page loads. However when I then also start editing the text in text-box manually and then go back to clicking on any of the hashtags they don't get appended on Firefox. On Chrome the most bizarre thing is happening - all the text I type manually gets replaced with the new hashtag and disappears.
I probably am doing something very wrong here, so I would appreciate if someone can point out my mistake here, and how to fix that.
Thanks.
2 things.
First, <textarea/> is not a valid tag. <textarea> tags must be fully closed with a full </textarea> closing tag.
Second, $(textarea).append(txt) doesn't work like you think. When a page is loaded the text nodes inside the textarea are set the value of that form field. After that, the text nodes and the value can be disconnected. As you type in the field, the value changes, but the text nodes inside it on the DOM do not. Then you change the text nodes with the append() and the browser erases the value because it knows the text nodes inside the tag have changed.
So you want to set the value, you don't want to append. Use jQuery's val() method for this.
$(document).ready(function(){
$(".hashtag").click(function(){
var txt = $.trim($(this).text());
var box = $("#text-box");
box.val(box.val() + txt);
});
});
Working example:
http://jsfiddle.net/Hhptn/
Use the val() function :)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="hashtag">#one</div>
<div class="hashtag">#two</div>
<form accept-charset="UTF-8" action="/home/index" method="post">
<textarea id="text-box"></textarea>
<input type="submit" value ="ok" id="go" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$(".hashtag").click(function(){
var txt = $.trim($(this).text());
$("#text-box").val($("#text-box").val() + txt);
});
});
</script>
</body>
</html>
Does that help?
The reason append does not seem to work is because the value of the textarea is made up of the child node, but by treating it as multiple seperate nodes the screen won't update, according to my Firebug. Firebug will show me the updated child nodes, but NOT the text I typed manually into the textarea, whereas the screen shows me the manually typed text but not the new nodes.
You can reference by value of textarea.
$(document).ready(function () {
window.document.getElementById("ELEMENT_ID").value = "VALUE";
});
function GetValueAfterChange()
{
var data = document.getElementById("ELEMENT_ID").value;
}
works fine.
if(data.quote) $('textarea#message').val($('textarea#message').val()+data.message +' ').focus();

Categories