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>
Related
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>
I have a JavaScript function:
function addcontent(ele, text, lines, separate_lines){
if(separate_lines){
for(i=0; i<lines; i++){
text=text+"\n"+text+"\n";
}
}
else if(!separate_lines){
for(e=0; e<lines; e++){
text=text+text;
}
}
ele.append(text);
}
and when I use it for the onclick of an HTML Button like:
<button onclick="addcontent(document.body, 'A', 100, true)">
Add content.
</button>
I get this error in the Chrome console when I click the button:
Uncaught RangeError: Invalid string length
at addcontent
at HTMLButtonElement.onclick
I have no idea where I'm wrong.
The issue is that on each iteration you add the text two times, but you assign the result to text again.
iteration 1: A + A = AA (but you assign to text) so
iteration 2: AA + AA = AAAA
iteration 3: AAAA + AAAA = AAAAAAAA
iteration 4: AAAAAAAA + AAAAAAAA = AAAAAAAAAAAAAAAA
etc
So it is exponential. You are basically doing 2lines insertion of the text. You can guess that this creates a "quite" large string and it cannot be handled.
Use a different variable for the generated text.
function addcontent(ele, text, lines, separate_lines) {
let finalText = text;
if (separate_lines) {
for (let i = 0; i < lines; i++) {
finalText = finalText + "\n" + text;
}
} else {
for (let e = 0; e < lines; e++) {
finalText = finalText + text;
}
}
ele.append(finalText);
}
<button onclick="addcontent(document.body, 'A', 100, true)">
Add content.
</button>
It's the old Wheat and chessboard problem, the string is simply way too long.
You double the string for 100 times that's 2^100...
It works fine with say lines = 10
This problem can be resolved if you can do as:
text = (text + "\n").repeat(lines * 2);
function addcontent(ele, text, lines, separate_lines) {
if (separate_lines) {
text = (text + "\n").repeat(lines * 2);
} else if (!separate_lines) {
for (e = 0; e < lines; e++) {
text = text + text;
}
}
ele.append(text);
}
<button onclick="addcontent(document.body, 'A', 100, true)">
Add content.
</button>
If you want to add new line in after A
function addcontent(ele, text, lines, separate_lines) {
if (separate_lines) {
text = `${text}<br>`.repeat(lines * 2);
} else if (!separate_lines) {
for (e = 0; e < lines; e++) {
text = text + text;
}
}
ele.innerHTML = text;
}
<button onclick="addcontent(document.body, 'A', 100, true)">
Add content.
</button>
enter image description here
How can I convert each alternate character of a string lowercase to uppercase and string uppercase to lowercase in Jquery?
You can check if the character of the string is uppercase by comparing the ASCII code. If it's between 65 & 90, the character is in uppercase.
Then by applying toUpperCase & toLowerCase methods will transform uppercase alphabets into lowercase and vice-versa.
function isUpperCase(c) {
return c >= 65 && c <= 90;
}
var string = "AaBbCcDd *+-";
var updatedString = string.split("").map(c => isUpperCase(c.charCodeAt(0)) ? c.toLowerCase() : c.toUpperCase()).join("");
console.log("Original String:: " + string);
console.log("Transformed String:: " + updatedString);
You can use this code alternate character
function alternate(changeString) {
var charArray = changeString.toLowerCase().split("");
for (var i = 1; i < charArray.length; i += 2) {
charArray[i] = charArray[i].toUpperCase();
}
return charArray.join("");
};
var text = "Test";
console.log(alternate(text));
For the transformation, you can use the following:
function isLowerCase(character) {
return "abcdefghijklmnopqrstuvwxyz".indexOf(character) >= 0;
}
function convertChar(character) {
return isLowerCase(character) ? character.toUpperCase() : character.toLowerCase();
}
function convert(str) {
var result = "";
for(var i = 0; i < str.length; i++) {
result += convertChar(str[i]);
}
}
A complete example here: (although it isn't exact the same that is in your pic)
function isLowerCase(character) {
return "abcdefghijklmnopqrstuvwxyz".indexOf(character) >= 0;
}
function convertChar(character) {
return isLowerCase(character) ? character.toUpperCase() : character.toLowerCase();
}
function convert(str) {
var result = "";
for(var i = 0; i < str.length; i++) {
result += convertChar(str[i]);
}
return result;
}
$('#text').on('input', function(){
$('#display').val(convert(this.value));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>input</label><input id="text" />
<label>display</label><input id="display" disabled />
Please refer below code may be it will help you,
Keyup event will work each character
$(document).ready(function(){
var upperCase= new RegExp('[A-Z]');
var lowerCase= new RegExp('[a-z]');
$("#text").keyup(function(){
var l =this.value.length;
var s =this.value;
var r =new Array();
for(var i=0;i<l;i++){
if(upperCase.test(s[i])){
r.push(s[i].toString().toLowerCase());
}
if(lowerCase.test(s[i])){
r.push(s[i].toString().toUpperCase());
}
}
$("#res").val(r.toString().replace(/\,/g, '').trim());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text">
<br>
Result:<input type="text" id="res">
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/>',
...
];
I'm working on a simple JS code to replace some words with others in a text using an array.
<textarea id="text1">
e mi e
ke fo
e di
</textarea>
<button type="button" onclick="myFunction()">try</button>
<pre id="demo"></pre>
<script>
function myFunction() {
var str = document.getElementById("text1").value;
var mapObj = {
"k":"g",
" e": "B",
"e":"ar"
};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.toLowerCase().replace(re, function(matched){
return mapObj[matched];
});
document.getElementById("demo").innerHTML = str;
}
</script>
The result is:
ar mi B
gar fo
ar di
But I desire to have this:
B mi B
gar fo
B di
If "e"s are to be changed before " e"s (separated e with a space before it), then " e"s will not be " e" but "ar", so in the array, I've put " e" above "e" and it works well.
However the problem is that the text may contain a separated "e" as the first word of the whole text or as the first word of a line with no space before it. When it's the case how can I replace this separated "e"with "B" and prevent it from being replaced with "ar".
The problem with your current code is that the .replace function is only taking a single variable input. This limits you from using more specific RegExp in your replace, as the matched element will not match the regex.
.replace's function option provides access to matched groups as the 1+nth variables. As a result we can leverage this to lookup our replacement strings in an array.
By utilising RegExp groups we can capture the values we're looking for and replace them as needed.
JS
var myFunction = function() {
var str = document.getElementById("text1").value;
var regexs = ['(k)','(^e|\\se)', '(e)'];
var replacers = ['g', 'B', 'ar'];
var re = new RegExp(regexs.join("|"),"gi");
// you would need to add variables to the function for each matching group you add (currently there are 3 so we have 3 groups)
str = str.toLowerCase().replace(re, function(raw, group0, group1, group2){
if(typeof group0 !== "undefined"){
return replacers[0]; // replaces with 'g'
}else if(typeof group1 !== "undefined"){
// skip over the first character (white space) and concatenate the replacement
return raw[0] + replacers[1]; // replaces with 'B'
}else if(typeof group2 !== "undefined"){
return replacers[2]; // replaces with 'ar'
}
return raw;
});
document.getElementById("demo").innerHTML = str;
};
document.getElementById('go').addEventListener('click', myFunction);
CSS
#demo{
white-space:pre;
}
NOTE: because you're outputting to an elements .innerHTML without the above CSS new lines are not displayed.
JS FIDDLE
Try The below code.
function myFunction() {
var str = document.getElementById("text1").value;
str = str.toLowerCase().split('k').join('g').split(' e').join(' B').split('\\n').join(' B').split('e').join('ar');
document.getElementById("demo").innerHTML = str;
}
Its a different approach but I got the expected output.
A simple workaround.
<script type="text/javascript">
var myfunction = function(){
var f = document.getElementById('text1').innerHTML;
var c = f.replace(/e/ig,'ar').replace(/\bar/ig,'B').replace(/k/ig,'g');
document.getElementById('text1').innerHTML = c;
}
</script>
This works.
<textarea id="source" cols="5" rows="5">
e mi e
ke fo
e di
</textarea>
<button type="button" onclick="convert()">Convert</button>
<textarea id="destination" cols="5" rows="5">
</textarea>
<script>
function replaceWord(searchFor, replaceWith, paragraph) {
if (paragraph) {
var lines = paragraph.split('\n');
for (lineNo = 0; lineNo < lines.length; lineNo++) {
var words = lines[lineNo].split(' ');
for (wordNo = 0; wordNo < words.length; wordNo++) {
if (words[wordNo] === searchFor) {
words[wordNo] = replaceWith;
}
}
lines[lineNo] = words.join(' ');
}
paragraph = lines.join('\n');
}
return paragraph;
}
function replaceWords(wordMap, paragraph) {
for(var searchFor in wordMap)
{
if(wordMap.hasOwnProperty(searchFor))
{
paragraph = replaceWord(searchFor, wordMap[searchFor], paragraph);
}
}
return paragraph;
}
function convert() {
var mapObj = {
"ke":"gar",
"e": "B"
};
var source = document.getElementById("source");
var destination = document.getElementById("destination");
destination.value = replaceWords(mapObj, source.value);
}
</script>
Here is the jsFiddle.
https://jsfiddle.net/1egs7zgc/
For what it's worth, your mapObj isn't really an array it's an object.