How to make paragaph effect after 2 enter or \n? - javascript

If you follow the script below, when you enter 1 time. Then it will be a paragraph. How to bring up paragraph after 2 or more enter? Because in the code, there is \n
$(document).ready(function() {
$('.button').on("click", function() {
var gogel = $('#mytxtarea').val();
$('#posttextareadisplay').html(telol(gogel));
});
$('#mytxtarea').on("input propertychange", function() {
var gogel = $('#mytxtarea').val();
$('#posttextareadisplay').html(telol(gogel));
});
})
function telol(str) {
$format_search = [
/\r\n|\r|\n|\n\r/g,
/(.*?)\001/g,
/\[arab\](.*?)\[\/arab\]/ig,
/\[b\](.*?)\[\/b\]/ig,
/\[i\](.*?)\[\/i\]/ig,
/\[u\](.*?)\[\/u\]/ig,
/\[\*\](.*?)(\n|\r\n?)/ig,
/\[ul\]/ig, /\[\/ul\]/ig,
/\[ol\]/ig, /\[\/ol\]/ig,
/\[url\](.*?)\[\/url\]/ig,
];
$format_replace = [
'\001',
'<p>$1</p>',
'<span class="lbs0">$</span>',
'<b>$1</b>',
'<em>$1</em>',
'<span style="text-decoration: underline;">$1</span>',
'<li>$1</li>',
'<ul>', '</ul>',
'<ol>', '</ol>',
'$1',
];
for (var i = 0; i < $format_search.length; i++) {
var arrText = str.trim().split(/\r|\n|\n\r|\r\n/);
var newText = '';
$.each(arrText, function(i, text) {
if (text.length < 1 || text == "\r\n" || text == "\n" || text == "\r" || text == "\n\r") {
return true;
}
newText += text.trim() + '\n';
});
str = newText.replace($format_search[i], $format_replace[i]);
}
return str;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form1" method="post" action="">
<p>
<textarea name="mytxtarea" id="mytxtarea" class="ed">This is a sample text</textarea>
</p>
<p id="posttextareadisplay"></p>
<p>
</p>
</form>
OR LOGIC like this
A variable passed from PHP as below:
This is man.
Man like dog.
Man like to drink.
Man is the king."
I would like my result to look something like this after the Javascript converts it:
This is man<br />Man like dog. Man like to drink.<br />Man is the king."

Try this code. It show text on clicking 2 times on the button , by using $('.button').on('dblclick',function{........});
$(document).ready(function() {
$('.button').on("dblclick", function() {
var gogel = $('#mytxtarea').val();
$('#posttextareadisplay').html(telol(gogel));
});
$('#mytxtarea').on("input propertychange", function() {
var gogel = $('#mytxtarea').val();
$('#posttextareadisplay').html(telol(gogel));
});
})
function telol(str) {
$format_search = [
/\r\n|\r|\n|\n\r/g,
/(.*?)\001/g,
/\[arab\](.*?)\[\/arab\]/ig,
/\[b\](.*?)\[\/b\]/ig,
/\[i\](.*?)\[\/i\]/ig,
/\[u\](.*?)\[\/u\]/ig,
/\[\*\](.*?)(\n|\r\n?)/ig,
/\[ul\]/ig, /\[\/ul\]/ig,
/\[ol\]/ig, /\[\/ol\]/ig,
/\[url\](.*?)\[\/url\]/ig,
];
$format_replace = [
'\001',
'<p>$1</p>',
'<span class="lbs0">$</span>',
'<b>$1</b>',
'<em>$1</em>',
'<span style="text-decoration: underline;">$1</span>',
'<li>$1</li>',
'<ul>', '</ul>',
'<ol>', '</ol>',
'$1',
];
for (var i = 0; i < $format_search.length; i++) {
var arrText = str.trim().split(/\r|\n|\n\r|\r\n/);
var newText = '';
$.each(arrText, function(i, text) {
if (text.length < 1 || text == "\r\n" || text == "\n" || text == "\r" || text == "\n\r") {
return true;
}
newText += text.trim() + '\n';
});
str = newText.replace($format_search[i], $format_replace[i]);
}
return str;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form1" method="post" action="">
<p>
<textarea name="mytxtarea" id="mytxtarea" class="ed">This is a sample text</textarea>
</p>
<p id="posttextareadisplay"></p>
<p>
</p>
</form>
<button class="button">
click here
</button>

In your format search and replace arrays, you're looking for a new line character from any major OS, and then replacing that as /001, which is next converted to a paragraph <p> element.
If you want, for instance, a single line break <br/> tag when there is only 1 carriage return, you could first look for \n\n (in all forms) and define those as \001, and then go back and look for all single newlines \n and define those as \002.
Then, whenever you see \001, it will be a <p> tag as you have it, and whenever you see a \002, it should be converted into a <br/>.
$format_search = [
/\r\n\r\n|\r\r|\n\n|\n\r\n\r/g,
/\r\n|\r|\n|\n\r/g,
/(.*?)\001/g,
/(.*?)\002/g,
...
];
$format_replace = [
'\001',
'\002',
'<p>$1</p>',
'$1<br/>',
...
];

Related

How do i remove a calculator from a bot? (its connected to the enter button)

I need to remove the calculator, without removing the function of allowing it to print, I have tried switching things around, and removing things, but still when I type in a number, such as 67, it comes out as 67=67, or more complicated math equations, it dosent except things like PI, this is because it thinks it's some symbol, not a character. The only things that do work are: / = + - /, it dosent accept cubed or squared, or to the power of X
Bot code:
<html>
<body>
<div class="container" id="content">
<p id="out">
</p>
<p id="inp">
<div id="stretchbox" style = "position:fixed; left:80px;">
<input type="text" placeholder="Coin ID #"
id="txt-inp"
autocomplete="off"
autocorrect="off"
autocapitalize="off"
autofocus="autofocus"
spellcheck="false">
</input>
</div>
</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(function() {
var trigger = [
["25184"],
["27123"],
["26124"],
["17453"]
];
var reply = [
["Coin Bot - "],
["Tokyn Blast - "],
["Iron Wolf - "],
["Foxyville - "],
];
var alternative = ["I cant find that Coin ID # right now, make sure that the Coin ID # exist!"];
let textInput = $('#txt-inp');
let messageOutput = $('#out');
let processingStatus = $('<span>Bot: Processing...<br></span>');
let name = 'You';
function println(text) {
let newSpan = document.createElement("SPAN");
let newLine = document.createElement("BR");
let textNode = document.createTextNode(text);
newSpan.appendChild(textNode);
document.getElementById("out").appendChild(newSpan);
document.getElementById("out").appendChild(newLine);
gotoBottom();
}
function print(text) {
let newSpan = document.createElement("SPAN");
let textNode = document.createTextNode(text);
newSpan.appendChild(textNode);
document.getElementById("out").appendChild(newSpan);
}
function gotoBottom() {
window.scrollTo(0,document.body.scrollHeight);
}
function sendMessage() {
let data = {
'reply': textInput.val()
};
if (!data['reply']) {
return;
}
println(name + ': ' + data['reply']);
textInput.val('');
messageOutput.append(processingStatus);
textInput.attr('disabled', 'disabled');
messageOutput.children().last().remove();
textInput.removeAttr('disabled');
output(data['reply']);
}
$('#txt-inp').keypress(function(e) {
if (e.which == 13) {
sendMessage();
}
});
function output(input){
try{
var product = input + "=" + eval(input);
} catch(e){
var text = (input.toLowerCase()).replace(/[^\w\s\d]/gi, ""); //remove all chars except words, space and
text = text.replace(/!/g, "!").replace(/i feel /g, "").replace(/whats/g, "what is").replace(/please /g, "").replace(/ please/g, "");
if(compare(trigger, reply, text)){
var product = compare(trigger, reply, text);
} else {
var product = alternative[Math.floor(Math.random()*alternative.length)];
}
}
println(product);
}
function compare(arr, array, string){
var item;
for(var x=0; x<arr.length; x++){
for(var y=0; y<array.length; y++){
if(arr[x][y] == string){
items = array[x];
item = items[Math.floor(Math.random()*items.length)];
}
}
}
return item;
}
});
</script>
</body>

feeding text into two text boxes and marking the same words

I have two fields - an input of type "text" and a textarea.
If the input contains the word "dog" and the textarea contains the word "underdog", the "dog" in the textarea should be marked in red in the div with the id "rslt".
How can I achieve this with jQuery?
You can use indexOf to get the position of the current word in a string then apply some css there. This code handles multiple word highlighting.
function markText(text, word, index) {
if (index != -1) {
var left = text.substr(0, index);
var current = word;
var right = text.substr(index + word.length);
var current = '<span style="background-color: red">' + current + '</span>';
text = left + current + right;
if (right.indexOf(word) >= 0) {
text = markText(text, word, (left + current).length + right.indexOf(word));
}
}
return text;
}
$('#btn').click(function () {
if (($('#txtarea').val() == "") || ($('#bx').val() == "")) {
$('#rslt').html('Please fill both boxes!');
return;
}
var words = $('#bx').val().split(' ');
var text = $('#txtarea').val();
words.forEach(function (word) {
if (text.indexOf(word) >= 0) {
text = markText(text, word, text.indexOf(word));
}
});
$("#rslt").html(text); //WHAT HERE?
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Write here:</p>
<input type="text" id="bx"/><br/>
<p>and here:</p>
<textarea cols="100" rows="8" id="txtarea"></textarea><br/>
<button id="btn">GO</button>
<hr/>
<div id="rslt"></div>

Add user input to array // Javascript

This is the code I have so far. When the user enters a word into the input box, I want that word to be stored in an array via the Add Word button. Once a number of words have been entered, the user clicks the Process Word button and I want all the words in the array to appear. How would I do this? Also could someone also explain why when nothing is entered into the input box "field is empty" does not appear?
function begin() {
var word = "List of words";
var i = returnword.length
if (userinput.length === 0) {
word = "Field is empty"
}
document.getElementById('message2').innerHTML = word
while (i--) {
document.getElementById('message').innerHTML = returnword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
var arrword = [];
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
Addword()
Your function contains an array arrword. If you keep it inside your function it will be reset every time you call the function. You need to keep your array of words outside the function
Empty input
The empty input message should be shown when you click on the Add word button. Check the input and display a message if needed
Display word
You can simply use join() to display you array
var arrayOfWord = [];
var inputElement = document.getElementById('userinput');
var errorElement = document.getElementById('error');
var wordsElement = document.getElementById('words');
function addWord() {
errorElement.innerHTML = "";
var word = inputElement.value;
if (word.trim() === "")
errorElement.innerHTML = "Empty input";
else
arrayOfWord.push(word);
inputElement.value = "";
}
function process(){
words.innerHTML = arrayOfWord.join(' - ');
}
#error {
color: tomato;
}
#words {
color: purple;
}
Enter a word <input id="userinput" /><button onclick="addWord()">Add word</button>
<div id="error"></div>
<button onclick="process()">Process</button>
<div id="words"></div>
you can do something a bit clearer with jQuery! :)
if you handle the input with jquery you can write something like:
var arrWord = [] // your array
/* Attaching a click handler on your "Add Word" button that will
execute the function on user click */
$("#addWordButtonID").on("click", function () {
var wordTyped = $('#textInputID').val() // your var that collect userInput
if (wordTyped.length != 0) { // your if statement with length === 0 condition
arrWord.push(wordTyped) // adding word typed to the array
}
})
to add jquery to your html page, just add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
in your html header
Hopefully you already have the right html. Then you can modify your script like below:
<script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
</script>
var arrword = [];
var returnword;
function begin() {
var word = "List of words";
var i = arrword.length;
if (arrword.length === 0) {
word = "Field is empty";
}
document.getElementById('message2').innerHTML = word;
while (i--) {
document.getElementById('message').innerHTML = arrword[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}
function addword() {
returnword = document.getElementById('userinput').value;
arrword.push(returnword);
}
<button id="addWord" onclick="addword()">Add Word</button>
<button id="processWords" onclick="begin()">ProcessWords</button>
<input type="text" id="userinput" value=" " />
<div id="message2">
</div>
<div id="message">
</div>

Reverse case (Lowercase/Uppercase) of an input value character by character

By using one input text box and the input type allows only alphabets.The value entered is 'a' and it should be display outside the textbox as 'A'?
If we enter the alphabet small 'a' on input text then it will wanted to display capital 'A' on the outside of the box...
The following is my html code:
<!DOCTYPE html>
<html>
<head>
<!--<script type="text/javascript" href="check.js"></script>-->
</head>
<body>
<input type="text">
<script>
function myFunction()
{
var A = document.getElementById('input').value;
console.log('alphabet'.toUpperCase());
}
</script>
</body>
</html>
To show the input value with case reversed you should:
Call your function in the onkeyup event of your input to update the preview immediately with the inputted string.
And loop through your string and for each character test if it's in
uppercase reverse it to lowercase or make it uppercase if it's
lowercase.
Here's a Snippet DEMO:
function myFunction() {
var A = document.getElementById('input').value;
var output = '';
for (var i = 0, len = A.length; i < len; i++) {
var character = A[i];
if (character == character.toLowerCase()) {
// The character is lowercase
output = output + character.toUpperCase();
} else {
// The character is uppercase
output = output + character.toLowerCase();
}
}
document.getElementById("preview").innerText = output;
}
<input id="input" type="text" pattern="[A-Za-z]" onkeyup="myFunction()" /><span id="preview"></span>
You may use an event for immediatly update the result, while writing.
document.getElementById('input').addEventListener('keyup', function () {
var input = document.getElementById('input').value;
if (!input.match(/^[a-z]*$/i)) {
document.getElementById('output').innerHTML = 'Wrong input';
return;
}
document.getElementById('output').innerHTML = input.split('').map(function (a) {
return a.match(/[a-z]/) ? a.toUpperCase() : a.toLowerCase();
}).join('');
});
<input type="text" id="input">
<div id="output"></div>
function reverseCase(str) {
let newstr = str.split('');
let newarr = [];
//return newstr;
for(i=0; i<newstr.length; i++) {
if(newstr[i] == newstr[i].toLowerCase()){
newarr.push(newstr[i].toUpperCase());
}else
if(newstr[i] == newstr[i].toUpperCase()){
newarr.push(newstr[i].toLowerCase());
}
} return newarr.join('');
}
console.log(reverseCase("Happy Birthday"))

Truncate text but keep html in javascript

I am printing a string some text, some other text.
I want to truncate the visible text, but keeping the link.
If I just did a naïve substring, I would mess up the html.
I want to make sure that only 100 characters are shown, but if the last part of the string is, for instance, <a hre, then this should be stripped as well.
Edit
I have tried
arr = ['some text', 'some other text', 'some third text'];
output = arr.map(el => '' + el + '').join(', ');
// print
console.log(output.substr(0, 20))
but this will cut off the html and output
<a href="#">some tex
But I want it to count the number of shown characters instead of how many characters were used to show the output.
So if the shown output is some text, some other text, some third text, I want it to cut it off at character 20 in the output text rather than character 20 in the html output.
Set textContent of elements to anything you want:
(function() {
var links = document.getElementsByClassName("link");
for(var i = 0; i < links.length; i++) {
links[i].textContent = "Link text changed";
}
})();
<a class="link" href="http://stackexchange.com">Stack Exchange</a>
<a class="link" href="http://stackoverflow.com">Stack Overflow</a>
You can do this with simple CSS.
var paragraph = document.querySelector('p#before');
document.querySelector('p#after-text').innerHTML = truncateTEXT(paragraph, 20, true);
document.querySelector('p#after-html').innerHTML = truncateHTML(paragraph, 20, true);
function truncateHTML(html, limit, dots) {
holdCounter = false;
truncatedHTML = '';
html = paragraph.innerHTML;
for(index = 0; index < html.length; index++) {
if(!limit) {
break;
}
if(html[index] == '<') {
holdCounter = true;
}
if(!holdCounter) {
limit--;
}
if(html[index] == '>') {
holdCounter = false;
}
truncatedHTML += html[index];
}
truncatedHTML = correctHTML(truncatedHTML);
if(dots) {
truncatedHTML = truncatedHTML + '...';
}
return truncatedHTML;
}
function truncateTEXT(string, limit, dots) {
string = string.innerText;
if(string.length > limit) {
return string.substring(0, limit) + (dots ? '...' : '');
} else {
return string;
}
}
function correctHTML(html){
container = document.createElement('div');
container.innerHTML = html
return container.innerHTML;
}
<p id="before">Lorem <strong>ipsum</strong> dolor <strong>sit</strong> amet <strong>consectetur</strong> adipiscing <strong>elit</strong></p>
<p id="after-text"></p>
<p id="after-html"></p>

Categories

Resources