Censoring / Highlighting using JavaScript - javascript

I'm trying to create a small sample application for highlighting / censoring of a textarea using JavaScript. To start with I'm just trying to replace the letters, though once that is solved my plan was to use mark.js to mark censored words. Right now when I run my application I'm getting Uncaught TypeError: Cannot Read property 'value' of null on line 21.
<html>
<head>
<title>Syntax Highlighting</title>
</head>
<body>
<form name="badwords" method="post" action="" >
<textarea name="comments" rows="10" cols="60"></textarea>
<br />
<input id="formSub" type="submit" value="Submit!" />
</form>
</body>
<script type="text/javascript">
var div = document.getElementById('formSub');
function replaceWords(event) {
//Prevent form submission to server
event.preventDefault();
var commentContent = document.getElementById('comments');
var badWords = ["x", "y", "z"];
var censored = censore(commentContent.value, badWords);
}
function censore(string, filters) {
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
//replace each letter with a star
var stars = '';
for (var i = 0; i < match.length; i++) {
stars += '*';
}
return stars;
});
}
div.addEventListener('click',replaceWords);
</script>
</html>

<html>
<head>
<title>Syntax Highlighting</title>
</head>
<body>
<form name="badwords" method="post" action="" >
<textarea id="pesho" name="comments" rows="10" cols="60"></textarea>
<br />
<input id="formSub" type="submit" value="Submit!" />
</form>
</body>
<script type="text/javascript">
var div = document.getElementById('formSub');
function replaceWords(event) {
//Prevent form submission to server
event.preventDefault();
var commentContent = document.getElementById('pesho');
var badWords = ["crap", "fuck", "cunt"];
console.log(commentContent.value)
commentContent.value =censore(commentContent.value, badWords);
}
function censore(string, filters) {
console.log('in')
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
//replace each letter with a star
var stars = '';
for (var i = 0; i < match.length; i++) {
stars += '*';
}
return stars;
});
}
div.addEventListener('click',replaceWords);
</script>
</html>
As some of the other guys before me mentioned, you were not targeting the id of the text area but the name attribute, beside that for the function to make actual changes on the view you must change the targeted element value (see the modified example)

Related

Form Text Area creates a URL

I have a pretty simple need here.
I want to have a text area, that is populated with a line of ID's - each id will be on a new line.
How can I generate a URL from that?
12345
09876
Once submitted should generate to be https://xx.com/12345&09876
I have been using this Form value creates a URL and have changed it to text area, but cant get each line break to be changed to the '&' in the url string.
Any help would be amazing!
<script type="text/javascript">
function goToPage() {
var page = document.getElementById('page').value;
window.location = "https://google.com/" + page;
}
</script>
<textarea name="textarea" style="width:250px;height:150px;" id="page"></textarea>
<input type="submit" value="submit" onclick="goToPage();" />
You can split by \n to get the characters in each line and join by &, then remove the last character:
var url = txt.value.split("\n").join("&").slice(0, -1);
console.log(url);
<textarea id="txt">
12345
09876
</textarea>
In the case of a form:
txt.addEventListener('input', function(){
form.action = txt.value.split("\n").join("&").slice(0, -1);
console.log(form.action);
})
<textarea id="txt">
12345
09876
</textarea>
<form id="form">
<button>Submit</button>
</form>
In your particular case:
<textarea name="textarea" style="width:250px;height:150px;" id="page"></textarea>
<input type="submit" value="submit" onclick="goToPage();" />
<script type="text/javascript">
function goToPage() {
var page = document.getElementById("page").value.split("\n").join("&");
alert(page);
window.location = "https://google.com/" + page;
}
</script>
You can replace text in a string using the JavaScript replace function, as follows:
var newString = oldString.replace(/(\r\n|\r|\n)/g, '&');
This line takes the string variable oldString (which should contain the data with all of the linebreaks) and changes all of the linebreaks to ampersands. It uses something called a Regular Expression to find all of the line breaks.
So for your HTML:
<script type="text/javascript">
function goToPage() {
var page = document.getElementById('page').value;
window.location = "https://google.com/" + page.replace(/(\r\n|\r|\n)/g, '&');
}
</script>
<textarea name="textarea" style="width:250px;height:150px;" id="page"></textarea>
<input type="submit" value="submit" onclick="goToPage();" />
try splitting your text area by \n by doing so:
var split_text = your_text_area.split("\n"); // Replace your_text_area
The string which will be passed in the text area will be splitted by \n (newline) and every line will be inserted in the split_text variable, which is an array.
Then, you can generate a URL from the array like this:
var url = '';
for(let i = 0; i < split_text.length; i++)
{
url += split_text[i];
if((i+1) != split_text.length) // <-- Not the most optimized way to do it
{
url += "&";
}
}

I need to find the longest word in a sentence using JS

I am having trouble getting my JS to return the longest word when I click on the button. I am not sure what in my JS code I am missing or have put incorrectly, but when I type in three words nothing is given back to me. I have pasted below both my JS and html codes.
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Longest Word</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="p3-longest.js"></script>
</head>
<body>
<header>
<h1>Longest Word</h1>
</header>
<body>
<form action="demo_form.asp" id="demo_form">
Phrase:
<input type="text" id="input1" name="LongestWord" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="Longest Word">
</form>
</body>
</html>
JS:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length ; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
function init() {
alert('count words');
var countTag = document.getElementById('btn1');
countTag.onclick = longestWord(string);
}
window.onload = init;
try this:
Phrase:
<input type="text" id="input1" name="LongestWord" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="get Longest Word">
<br/>
Longest Word: <span id='sp1'></span>
<script>
var btn = document.getElementById("btn1");
var in1 = document.getElementById("input1");
var sp1 = document.getElementById("sp1");
btn.onclick = function(){
var vals = in1.value.split(' ');
var val = vals[0];
vals.forEach(function(v){ if(v.length>val.length) val = v;});
sp1.textContent = val;
}
</script>
Fiddle Demo
Add this to your button:
onClick="alert(longestWord(document.getElementById('input1').value))"
It will take the value of input1 and send it to your longestWord-function. Then put up an alert-box with the return value from your function.
I don't see anything particularly wrong with your code ... except for the fact that "I don't see any code here that will ever 'give anything back to you!'" :-)
Presumably, "onload", the init() function dutifully runs ... and setting countTag.onclick to whatever integer value longestWord() might return when given the undefined value of the non-declared non-variable length. (Which is of no good use at all to onclick, which expects a function, not an integer...)
None of which, even if it did work (which it doesn't ...), ever asks the digital computer to, by any means at all, "give anything back to you!"

How to make a word a link if the user has input # before it?

I am using this code:
<form oninput="x.value=a.value">Account Info <br>
<input type="text" id="a">First Name<br>
UserName <output name="x" for="a"></output>
</form>
I want i such a way that if the user inputs a word and he has place # before the word without space then how to make the word as a link. Means the tag which happens in facebook. Can it be done with java script and how.
This was just the example to demonstrate i want to intergrate this type in my project as comments. And it will be with php.
Thanks
Here's one example to check. It works with enter keypress and even prevents for adding same tags over again: http://codepen.io/zvona/pen/KpaaMN
<input class='input' type="text" />
<output class='output'></output>
and:
'use strict';
var input = document.querySelector('.input');
var output = document.querySelector('.output');
input.addEventListener('keyup', function(evt) {
if (evt.keyCode !== 13 || !input.value.length || ~output.textContent.indexOf(input.value)) {
return;
}
var tag = document.createElement('a');
tag.appendChild(document.createTextNode(input.value));
if (input.value.startsWith("#")) {
tag.setAttribute("href", input.value);
}
output.appendChild(tag);
input.value = "";
}, false);
<form>Account Info <br>
<input type="text" id="a">First Name<br/>
<output id="result" name="x" for="a"></output>
<button type="button" onclick="changeVal(document.getElementById('a').value)">Click</button>
</form>
<script>
function changeVal(value1){
var dt = value1.split(" ");
document.getElementById("result").innerHTML = "";
for(var t=0; t < dt.length; t++){
if(dt[t].startsWith("#")){
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" <a href='#'>"+dt[t]+"</a>";
}
else{
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" "+dt[t];
}
}
}
</script>
Checkout Jsfiddle demo
https://jsfiddle.net/tum32675/1/
You could use a textarea to input and a render to show the output. Then hiding the input and showing the output only. But that's another
story.
If you use a contentEditable div, you can actually insert and render the html from it in the same component. Check it out!
$(document).on("keyup","#render", function(){
var words = $(this).text().split(" ");
console.log(words);
if (words){
var newText = words.map(function(word){
if (word.indexOf("#") == 0) {
//Starts with #
//Make a link
return $("<div/>").append($("<a/>").attr("href", "#").text(word)).html();
}
return word;
});
}
$(this).empty().append(newText.join(" "));
placeCaretAtEnd( $(this)[0]);
});
Here is the Plunker
Thanks for the attention.

JavaScript Replace Method for multiple textboxes

Can anyone please tell me how I can use the replace method to replace a character if it occures in more than one textbox without having to write separate function for each textbox.
The code below is the basic way to use the replace method but it only allows for one textbox.
I'm sure I need a loop in there but I'm not sure how to use that without affecting the replace method.
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript">
function stringReplace(form) {
var replaceStr = form.textfield1.value
var pattern = /\'/g;
form.textfield1.value = replaceStr.replace(pattern, "''");
}
</script>
</head>
<body>
<form name="form1" method="post" action="JStest_redirect.asp">
<p>fname:
<input type="text" name="textfield1" size="20">
</p>
<p>lname:
<input type="text" name="textfield2" size="20">
</p>
<p>
<input onclick="return stringReplace(form)" type="submit" name="Submit" value="Submit">
</p>
</form>
</body>
</html>
You can do this:
function stringReplace(form) {
var $inputs = $(form).find('input:text');
var pattern = /\'/g;
$inputs.each(function () {
this.value = this.value.replace(pattern, "''");
});
return false; // Prevent the form from being submitted
}
This would find all the input type text within the form and replace their values.
If you wish to do it without jquery, you can use the getElementsByTagName() method.
function stringReplace(form) {
var pattern = /\'/g;
var inputs = form.getElementsByTagName("input");
var input;
for (var i = 0; i < inputs.length; i++) {
input = inputs[i];
if (input.type = 'text') {
var replaceStr = input.value;
input.value = replaceStr.replace(pattern, "''");
}
}
return false;
}
You seem to want
function stringReplace(form) {
$('input[type=text]').val(function(_, v) {
return v.replace(/\'/g, "''");
});
return false;
}
I added a return false at the end to prevent the form to be submitted on click. You probably want to have a separate button in your case.
I believe that fisrt you have to take all the values
function GetValue(){
var Contain = "";
$("#form1 :text").each(function(){
//add replace code here
});
}
You can add onchange function to all of you text input
function stringReplace(textField) {
var replaceStr = this.value
var pattern = /\'/g;
this.value = replaceStr.replace(pattern, "''");
}
and than you add
<input type="text" name="textfield1" size="20" onchange="stringReplace(this);">

html - Get wrapped text from textarea

I'm trying to get the word wrapped line breaks from a textarea without having make any server calls. This answer gets me 90% of the way there. The problem is that the page is reloaded inside of the iframe each time the submit button is clicked. Here's the code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<script type="text/javascript">
function getURLParameter(qs, name) {
var pattern = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(pattern);
var res = regex.exec(qs);
if (res == null)
return "";
else
return res[1];
}
function getHardWrappedText() {
var frm_url = document.getElementById('frame').contentDocument.URL;
var text = unescape(getURLParameter(document.getElementById('frame').contentDocument.URL, 'text')).replace(/\+/g, ' ');
return text;
}
function onIFrameLoad() {
var text = getHardWrappedText();
console.log(text);
}
window.onload = function() {
console.log("loading")
};
</script>
<form name="form" method="get" target="frame">
<textarea id="text" name="text" cols=5 wrap="hard">a b c d e f</textarea>
<input type="submit">
</form>
<iframe id="frame" name="frame" onload="onIFrameLoad()" style="display:none;"></iframe>
</body>
</html>
Clicking on the submit button gives the output:
loading
a b c d e
f
Is there a way to prevent the iframe from reloading the page?
You have to return a false to the onsubmit event of the form.
<form name="form" method="get" target="frame" onsubmit="onIFrameLoad">
If it is based on some condition that you do not want to load
function onIFrameLoad() {
var text = getHardWrappedText();
console.log(text);
if(text.indexOf('\n')<0) return false;
}
Am just putting a random thing at text.indexOf('\n')<0, you can have anything that makes sense or always return false (which looks unlikely)

Categories

Resources