Remove line with specific word from text area using javascript - javascript

I am trying to remove line with specific word using javascript from textarea.
Here is example
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
If the user enters the value in input field the line which contains it should be removed. Suppose user enters CxPh1tgiK2g or xOYPv7CxMVk the line which contains those ids should be removed

Try
$("#remove").click(function() {
var text = $("#id").val()
var lines = $('#textarea').val().split('\n');
lines = lines.filter(function(val) {
if (val.match(text)) return false
else return true
})
$('#textarea').text(lines.join('\n'))
})
$("#replace").click(function() {
var text = $("#id").val()
var lines = $('#textarea').val().split('\n');
var n = Math.floor(Math.random()*lines.length)
lines[n] = lines[n].replace(/\?v=([A-Za-z0-9]){11}/, "?v="+text)
$('#textarea').text(lines.join('\n'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="id" />
<input type="button" id="remove" value="Remove" />
<input type="button" id="replace" value="Replace" />
<br/>
<textarea id="textarea" rows="4" cols="150">
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
</textarea>

As solution to remove line with inclusion
var value = test.value.split(/\n/g).filter(function(val)
{
return val !== "";
});
console.log(value);
setTimeout(function()
{
var index = value.findIndex(function(val)
{
return val.includes('kKC7-ACrs1w');
});
if (index !== -1)
{
value.splice(index, 1);
test.value = value.join("\n");
}
}, 2000);
.text {
width: 100%;
resize: none;
height: 200px;
}
Line with <b>kKC7-ACrs1w </b>will be removed in 2 secs
<textarea name="" id="test" class=text >
www.youtube.com/watch?v=CxPh1tgiK2g&index=0&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=xOYPv7CxMVk&index=1&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=kKC7-ACrs1w&index=2&list=PLB03EA9545DD188C3
www.youtube.com/watch?v=qE2EuZZCMYE&index=3&list=PLB03EA9545DD188C3
</textarea>

You can do something like this:
var ta = document.querySelector("textarea");
var lines = ta.innerHTML.split("\n");
var id = "omg";
for (var i = 0; i < lines.length; i ++) {
if (lines[i].indexOf(id) > -1) {
lines.splice(i, 1);
}
}
ta.innerHTML = lines.join("\n");
<textarea>
lol
omg
js
</textarea>

Related

Get number of characters selected from a text inside textarea or input text [duplicate]

I am working on a project that requires me to count the number of characters entered in a text box and dynamically display the result elsewhere on the page.
As I said, this would preferably be done in jQuery or Javascript.
Thanks in advance.
You could do this in jQuery (since you said you preferred it), assuming you want the character count displayed in a div with id="characters":
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
UPDATE: jsFiddle (by Dreami)
UPDATE 2: Updating to include keydown for long presses.
This is my preference:
<textarea></textarea>
<span id="characters" style="color:#999;">400</span> <span style="color:#999;">left</span>
Then jquery block
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = [400- $(this).val().length];
$('#characters').text(cs);
}
<script type="text/javascript">
function countChars(countfrom,displayto) {
var len = document.getElementById(countfrom).value.length;
document.getElementById(displayto).innerHTML = len;
}
</script>
<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> characters entered.
Plain Javascript.
I would like to share my answer which i used in my project and it is working fine.
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="4" Columns="50" placeholder="Maximum limit: 100 characters"></asp:TextBox><br />
<span id="spnCharLeft"></span>
<script type='text/javascript'>
$('#spnCharLeft').css('display', 'none');
var maxLimit = 100;
$(document).ready(function () {
$('#<%= txtComments.ClientID %>').keyup(function () {
var lengthCount = this.value.length;
if (lengthCount > maxLimit) {
this.value = this.value.substring(0, maxLimit);
var charactersLeft = maxLimit - lengthCount + 1;
}
else {
var charactersLeft = maxLimit - lengthCount;
}
$('#spnCharLeft').css('display', 'block');
$('#spnCharLeft').text(charactersLeft + ' Characters left');
});
});
</script>
Source: URL
Though it has been already solved, I'm interested to share something that I have used in one of my projects:
<textarea id="message" cols="300" rows="200" onkeyup="countChar(this)"
placeholder="Type your message ..." >
</textarea>
<input id="text-character" class="input-mini uneditable-input"
placeholder="0 Chars" readonly />
<input id="text-parts" class="input-mini uneditable-input"
placeholder="0 Parts" readonly />
<input id="text-remaining" class="input-medium uneditable-input"
placeholder="160 Chars Remaining" readonly />
Javascript code:
function countChar(val) {
var len = val.value.length;
var ctext = len + " Chars";
var str = val.value;
var parts = [];
var partSize = 160;
while (str) {
if (str.length < partSize) {
var rtext = (partSize - str.length) + " Chars Remaining";
parts.push(str);
break;
}
else {
parts.push(str.substr(0, partSize));
str = str.substr(partSize);
}
}
var ptext = parts.length + " Parts";
$('#text-character').val(ctext);
$('#text-parts').val(ptext);
$('#text-remaining').val(rtext);
}
<script Language="JavaScript">
<!--
function Length_TextField_Validator()
{
var len = form_name.text_name.value.length; //the length
return (true);
}
-->
</script>
<form name="form_name" method="get" action="http://www.codeave.com/html/get.asp"
onsubmit="return Length_TextField_Validator()">
<input type="text" name="text_name">
<input type="submit" value="Submit">
</form>
Source(s) : Text Validation

How can I take text from <input> tag to javascript

I have made a program and it prompts the user to input text. Is there a way I can just take user input from the text box and then have the program take and use that text from there? Here's the code so far:
None of your corrections were working because I didn't tell you the what this program does. This program is supposed to take in a letter and then replace it with another letter encrypting the text, so I think that you need to see the entire code to figure this out;
function encodeFunction() {
var text = prompt("Enter Text");
document.getElementById("function").innerHTML = LetterChanges(text);
}
function decodeFunction() {
var text = prompt("Enter Text");
document.getElementById("function").innerHTML = LetterChanges(text, false);
}
function LetterChanges(str, encode = true) {
let adjust = 1;
if (!encode) {
adjust = -1;
}
}
}
str = str.toLowerCase();
let strArray = str.split("");
let letterChange = strArray.map(function(value, index, array){
if(str.charCodeAt(index) < 97 || str.charCodeAt(index) > 122){
return value
}else{
return String.fromCharCode(str.charCodeAt(index)+adjust)
}
});
return letterChange.join("");
}
<form>
<input type="text" id="EString" name="EString"> <br><br>
</form>
<button onclick="encodeFunction()">Encode String</button>
<button onclick="decodeFunction()">Decode String</button>
<p id="function"></p>
In your encode and decode functions, you can change:
var text = prompt("Enter Text");
to
var text = document.getElementById("EString").value;
If you'd like to get the value of the text input(id='EString') you can use
document.getElementById('EString').value
You could simply get the value of document.getElementById("EString"), e.g.
function encodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text);
}
function decodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text, false);
}
function LetterChanges(str, encode = true) {
let adjust = 1;
if (!encode) {
adjust = -1;
}
return str;
}
<form>
<input type="text" id="EString" name="EString"> <br><br>
</form>
<button onclick="encodeFunction()">Encode String</button>
<button onclick="decodeFunction()">Decode String</button>
<p id="function"></p>
function myChange(){
console.log(document.getElementById("EString").value);
}
<form>
<input type="text" onchange="myChange()" id="EString" name="EString" style=" width:1000px; height:500px;"></input>
</form>
Check the below code for your desired result:
function encodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text);
}
function decodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text, false);
}
function LetterChanges(str, encode=true) {
let adjust = 1;
if(!encode){
adjust = -1;
}
return adjust;
}
<form>
<input type="text" id="EString" name="EString" style=" width:1000px; height:500px;" /> <br><br>
</form>
<button onclick="encodeFunction()">Encode String</button>
<button onclick="decodeFunction()">Decode String</button>
<p id="function"></p>
I made some changes in your code.
<button onclick="encodeFunction()">Encode String</button>
<button onclick="decodeFunction()">Decode String</button>
<p id="function"></p>
<script>
function encodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text);
}
function decodeFunction() {
var text = document.getElementById("EString").value;
document.getElementById("function").innerHTML = LetterChanges(text, false);
}
function LetterChanges(str, encode=true) {
let adjust = 1;
if(!encode){
adjust = -1;
}
return "Text recieved in JavaScript: " + str;
}
</script>
Use oninput and onchange attributes in input tag to call javascript function, because oninput is not working in some browsers.

How to integrate counting frequency of characters in a string using javascript

I have some simple HTML code
<textarea id="text" placeholder="Type text...."></textarea>
<a id="button" class="button"></a>
<textarea id="result" disabled></textarea>
and I have a javascript code
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
I just want to integrate js with HTML to count each character frequency inside of textarea with id="text" and show result inside of textarea with id="result". I have tried to use
document.getElementById("text").value;
but something goes wrong and still not working. There is any way to do this in easy way?
If you want to do it while typing you can use the keyup event on the textarea, in the following way
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
window.addEventListener('load', function() {
const textbox = document.getElementById('text');
const result = document.getElementById('result');
textbox.addEventListener('keyup', function() {
const frequency = getFrequency( textbox.value );
result.value = Object.keys( frequency ).map( key => `${key}: ${frequency[key]}` ).join('\n');
});
});
<textarea id="text" placeholder="Type text...."></textarea>
<a id="button" class="button"></a>
<textarea id="result" disabled></textarea>
if you want to do it upon button click, you could change the previous code like so:
document.getElementById('button').addEventListener('click', function() {
const frequency = getFrequency( textbox.value );
result.value = Object.keys( frequency ).map( key => `${key}: ${frequency[key]}` ).join('\n');
});
This should do it.
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
document.getElementById('myButton').onclick = function(){
var str = document.getElementById('text').value;
var result = getFrequency(str);
document.getElementById('result').value = JSON.stringify(result);
}
<textarea id="text" placeholder="Type text...." ></textarea>
<button id="myButton" class="button">Count</button>
<textarea id="result" disabled></textarea>
Using spread syntax, Map, Array#reduce, and String#split
const textArea = document.getElementById("text");
const button = document.getElementById("button");
const result = document.getElementById("result");
button.addEventListener("click", function(){
const value = textArea.value.trim();
const res = getFrequency(value);
console.log(JSON.stringify([...res]));
result.innerText = `(${[...res].join("), (")})`;
})
function getFrequency(str){
return str.split("").reduce((a,c)=>a.set(c, (a.get(c) || 0) + 1), new Map());
}
div {
display: flex;
background-color: lightgrey;
flex-direction: column;
}
div > div {
flex-direction: row;
}
<div>
<textarea id="text" placeholder="Type text....">
Some text to check the count of characters
</textarea>
<div>
<button id="button" class="button">Click me</button>
<p id="result"></p>
</div>
</div>

Insert HTML in Div with a substr

I am trying to insert an underline or blank space in a div that is being affected with a keyup function. The objective is to be able to move where the blank space is in the text. The keyup function works fine, the inserting of the blank space (div class underline) isnt.
HTML:
<div class="bigwhitecard" id="bigwhitecard"></div>
<textarea id="text" placeholder="Type your card here" name="text"></textarea>
Javascript/Jquery:
$(document).ready(function () {
$('#text').keyup(function(){
$('#bigwhitecard').html($(this).val());
});
var blankplace = 0;
$('#rightbtn').click(function() {
blankplace++;
});
$('#leftbtn').click(function() {
blankplace--;
});
var b = '<div class="underline"></div>';
$('#bigwhitecard').each(function() {
var blankplace = 0;
var txt = $(this).text();
if (txt.length>0) {
$(this).html(''+txt.substring(0,blankplace)+'<div class="underline"> </div>');
}
});
});
So use a substr to get the remaining text length that is left over and add it after the text.
var filler = "__________";
var out = document.getElementById("bigwhitecard");
document.getElementById("text").addEventListener("keyup", function() {
var txt = this.value,
placeholder = txt.length<filler.length ? '<span class="underline">' + filler.substr(0,filler.length-txt.length) + '</span>' : '';
out.innerHTML = txt + placeholder;
});
.underline {
text-decoration: underline
}
<div class="bigwhitecard" id="bigwhitecard"></div>
<textarea id="text" placeholder="Type your card here" name="text"></textarea>
And based on your comment
var out = document.getElementById("bigwhitecard");
document.getElementById("text").addEventListener("keyup", function() {
var txt = this.value,
ind = 6,
len = this.value.length,
pre = len > ind ? txt.substr(0,ind) : txt,
suf = len > ind ? txt.substr(ind) : "";
out.innerHTML = pre + "<span>_</sapn>" + suf;
});
.underline {
text-decoration: underline
}
<div class="bigwhitecard" id="bigwhitecard"></div>
<textarea id="text" placeholder="Type your card here" name="text"></textarea>

Textarea validation by javascript

there are 2 kinds radio buttons.
If check sms button, then textarea's maxlength sets 90 bytes
If check lms button, then testarea's maxlength sets 2000 bytes
and We can check how many I put texts on the textarea at 'totalWordLimit'
but have problems
If I put many texts by copy & paste, textarea become disabled
and also when I change radio buttons, counting number doesn't initialize.
What I need to fix in this code?
<script type="text/javascript">
var setTotalNumberOfWordCounter = "90";
function displayWordCounter(){
var getTextValue = document.smsForm.msg.value; // Get input textarea value
var getTextLength = getTextValue.length; // Get length of input textarea value
var one_char = "";
var rbyte = 0;
var rlen = 0;
for(var i=0; i<getTextLength; i++){
one_char = getTextValue.charAt(i);
if(escape(one_char).length > 4){
rbyte += 2; // special language(2Bytes)
}else{
rbyte++; // 1Byte
}
if(rbyte <= setTotalNumberOfWordCounter){
rlen = i+1; //return text count
}
}
if(rbyte > setTotalNumberOfWordCounter){ //compare this length with total count
getTextValue = getTextValue.substring(0,setTotalNumberOfWordCounter);
document.smsForm.msg.value =getTextValue;
return false;
}
document.smsForm.totalWordLimit.value = (setTotalNumberOfWordCounter-rbyte);
var tt = document.getElementById("Textarea");
if(document.smsForm.totalWordLimit.value === "0"){
tt.value = tt.value.substring(0, tt.value.length-1);
}
}
</script>
<script type="text/javascript">
function ShowHide() {
var Textarea = document.getElementById("Textarea");
if(document.getElementById('sms').checked) {
setTotalNumberOfWordCounter = "90";
}else if(document.getElementById('lms').checked) {
setTotalNumberOfWordCounter = "2000";
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="sms" id="sms" onclick="ShowHide()" value="ss" checked>SMS
<input type="radio" name="lms" id="lms" onclick="ShowHide()" value="ll"> LMS
<textarea name="msg" class="main_txt_area" id="Textarea" onkeydown="return displayWordCounter();" cols="40" rows="10" ></textarea>
<script type="text/javascript">
document.write("<div class='total_count'>total remaining Charatctor: <input type='text' class='show_count' name='totalWordLimit' size=4 readonly value="+setTotalNumberOfWordCounter+"></div>");
</script>
Try this one
function ShowHide() {
var Textarea = document.getElementById("Textarea");
if(document.getElementById('sms').checked) {
Textarea.setAttribute("maxlength", "90");
}else if(document.getElementById('lms').checked) {
Textarea.setAttribute("maxlength", "2000");
}
}
and try onpaste function in the textarea element
<textarea name="msg" class="main_txt_area" id="Textarea" onkeydown="return displayWordCounter();" cols="40" rows="10" onpaste="return displayWordCounter();"></textarea>

Categories