Create Dynamic columns from big text data Javascript - javascript

I get the text dynamically, sometimes the text is short sometime the text long.
The Designer separate the text to tow columns.
How can I seperate the text to tow columns.
I use angular but simple javascript is ok.

Considering that you are using bootstrap column layout, you can divide the string content into two equal parts (space as a breaking point) and then you can construct a html string like this:
function splitInHalf(s){
var middle = Math.floor(s.length / 2);
var before = s.lastIndexOf(' ', middle);
var after = s.indexOf(' ', middle + 1);
if (middle - before < after - middle) {
middle = before;
} else {
middle = after;
}
var s1 = s.substr(0, middle);
var s2 = s.substr(middle + 1);
return [s1, s2];
}
var x = <you big or small string of content>;
var splitX = splitInHalf[x];
var _html = '<div class="col-lg-6">'+splitX[0]+'</div><div class="col-lg-6">'+splitX[1]+'</div>'
// Now set this _html as your html

Related

Adding style tags around specific characters only

I am trying to add inline styling to only numbers in paragraph elements. For example:
<p>This paragraph has the numbers 1 and 2 in it.</p>
So in this instance, I would want to put <span class="style">1</span>and <span class="style">2</span>. Around the two numbers in that paragraph.
I am trying to write a javascript to accomplish this so I don't have to go back into the document I'm working on and manually add the styling tags around each number, as the document is very long.
So far this is what I wrote, but I'm having difficulty figuring out what to do for the next step on how to incorporate the edits back into the paragraph HTML.
let regEx=/[0-9]/g;
let list = [];
let paragraphs = document.getElementsByTagName("p");
for (var i = 0; i < paragraphs.length; i++) {
let html = paragraphs[i].innerHTML;
list.push(html);
}
// all paragraphs into one string.
let joined = list.join(' ');
// all the numbers in the paragraphs stored in array
let numbers = joined.match(regEx);
// define array for styling edits
let edits = [];
// adding the styling tags to each num
numbers.forEach(function(num){
edits.push('<span class="style">' + num + '</span>');
// outputs ["<span class='style'>3</span>", "<span class='style'>7</span>", "<span class='style'>4</span>", "<span class='style'>5</span>"]
});
// need to insert edits into paragraph html
If anyone can offer any suggestions on how I might be able to accomplish this that would be great, I am still relatively new to working with JS.
const paragraphs = document.getElementsByTagName("p");
for (var i = 0; i < paragraphs.length; i++) {
const regEx=/([0-9])/g;
const newHtml = paragraphs[i].innerHTML.replace(regEx, '<span class="style">$1</span>');
paragraphs[i].innerHTML = newHtml;
}
I updated your regex to put the number in a group, then in the string replace you can reference that group, since there is only one it will be $1. As you can see in the replace we are wrapping that with the appropriate span and then plugging it right back into the innerHTML.
I did notice that your regex is only capturing single digit numbers, if you wanted to capture multi-digit numbers, you could update your reg ex like this: /([0-9]+)/g.
I created a simple jsfiddle to show you how it works: https://jsfiddle.net/andyorahoske/dd6k6ekp/35/
I broke out the most fundamental part of this into a reusable function that you may find helpful in other contexts.
/**
* Wraps numbers in a string with any provided wrapper.
* #param {String} str A string containing numbers to be wrapped.
* #param {String} wrapper A string with placeholder %s to define the wrapper. Example - <pre>%s</pre>
* #return {String} The original string with numbers wrapped using the wrapper param.
*/
function wrapNumbers(str, wrapper) {
var numbersInStr = str.match(/\d+/g) || [];
var chunks = [];
var segmentStart = 0;
for(var i = 0; i < numbersInStr.length; i += 1) {
var number = numbersInStr[i];
var indexOfNumber = str.indexOf(number);
var fWrapper = wrapper.replace('%s', number);
chunks.push(str.slice(segmentStart, indexOfNumber));
chunks.push(fWrapper);
segmentStart = indexOfNumber + number.length;
}
if(segmentStart < str.length) {
chunks.push(str.slice(segmentStart, str.length));
}
return chunks.join('');
}
To use this in your use case it might look like the following:
var paragraphs = document.getElementsByTagName("p");
var wrapper = '<span class="style">%s</span>';
for(var i = 0; i < paragraphs.length; i += 1) {
var paragraph = paragraphs[i];
paragraph.innerHTML = wrapNumbers(paragraph.innerHTML, wrapper);
}
Codepen: https://codepen.io/bryceewatson/pen/vRqeVy?editors=1111
Here's a new code https://jsfiddle.net/fazanaka/au4jufrr/1/
var element = document.getElementById('text'),
text = element.innerText,
wordsArray = text.split(' '),
newString;
for(var i = 0; i < wordsArray.length; i++){
if(!isNaN(parseFloat(wordsArray[i])) && isFinite(wordsArray[i])){
wordsArray[i] = "<span class='style'>" + wordsArray[i] + "</span>";
}
}
newString = wordsArray.join(' ');
element.innerHTML = newString;
I hope it helps you
UPD:
For all paragraphs https://jsfiddle.net/fazanaka/qx2ehym4/

Textarea limit characters and lines with Javascript

There are some similar topics to this theme, but current requirements are more specific and I couldn't combine it yet with existent solutions, so asking community to help me with. I need to build textarea js validator for rules:
4 lines of 32 characters maximum
of 128 characters maximum
a remaining characters counter is displayed under the textarea
and other that I already found how to do...
Could you please tell how I could implement this?
p.s. It should be clear Javascript solution
This is how your code should look like (see also JSFiddle):
var rows = 4;
var cols = 32;
var body = document.body;
var ta = createElem(body, 'textarea');
var div = createElem(body, 'div');
ta.rows = rows;
ta.cols = cols;
ta.addEventListener('keyup', () => {
var lines = ta.value.split('\n');
lines = lines
.slice(0, Math.min(lines.length, rows))
.map(line => line.substring(0, cols));
ta.value = lines.join('\n');
displayRemaining(cols * rows - ta.value.length + rows - 1);
});
displayRemaining(cols * rows);
function createElem(a, b){
b = document.createElement(b);
a.appendChild(b);
return b;
}
function displayRemaining(a){
div.innerHTML = 'Characters remaining: ' + a + '.';
}

How to add a common string in every randomly generated string Javascript

I am generating random strings using the below function in node.js. I wanted to know if there is any way to create text strings appropriately with a common string within every randomly generated string.
EDIT: The common string can be in any location of the generated string
For example:
Randomly generated string - Cxqtooxyy4
Can I add 'abc' or 'ABC' within that string like this - Cxqtoabcoxyy4 or CxqtoABCoxyy4 respectively.
My Code -
var randomTextArrayGeneration = function(size)
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0;i<size;i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
Can anyone tell me how do I do this? Any help is really helpful.
var n = text.length; //The size of your random string
var randomPosition = Math.floor((Math.random() * n) + 1); //Generate a random number between 1 and the size of your string
//Separate your string in 2 strings
var text1 = text.substring(1, randomPosition);
var text2 = text.substring(randomPosition, n);
//Create your final string by adding the common string between your two halves
var textFinal = text1 + commonString + text2;
return textFinal;
I don't remember how exactly works .substring(), you may want to change 1 by 0 in some places.
A rough sketch of the algorithm is this:
create random string of length size - <FIXED_STRING>.length
append <FIXED_STRING> to the end of generated string
Done.
A corner case is if size < <FIXED_STRING>.length, here you would need to provide some more discussion on what should happen.
You can use String.prototype.slice() to select 0-n characters from possible to insert into random index within string returned from randomTextArrayGeneration. If 0 is passed to randomTextArrayGeneration the selected string from possible will be set as result
var randomTextArrayGeneration = function(size, from, to) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < size; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
};
var len = Math.floor(Math.random() * text.length - 3);
var res = text.slice(0, len) + possible.slice(from, to).toLowerCase() + text.slice(len);
return res
}

textarea - how to count wrapped lines/rows

I need some function That will count rows ( i know that on stackoverflow there are more than hundreds of these questions) but in my case i need to count them even when there is no end of line (mean "/n") because typical function is
textarea.value.substr(0, textarea.selectionStart).split("\n").length;.
It means that if user overflows max length of the row but he doesn't use "enter" and the text is on "new line".
Well, i dont know how to describe it better, so there is a example on fiddle https://jsfiddle.net/fNPvf/12872/
try to write long sentence with no spaces, enters etc.. and you will see where the problem is
what i really don't want is css rule nowrap, overflow-x etc..
Here you go.
/** #type {HTMLTextAreaElement} */
var _buffer;
/**
* Returns the number of lines in a textarea, including wrapped lines.
*
* __NOTE__:
* [textarea] should have an integer line height to avoid rounding errors.
*/
function countLines(textarea) {
if (_buffer == null) {
_buffer = document.createElement('textarea');
_buffer.style.border = 'none';
_buffer.style.height = '0';
_buffer.style.overflow = 'hidden';
_buffer.style.padding = '0';
_buffer.style.position = 'absolute';
_buffer.style.left = '0';
_buffer.style.top = '0';
_buffer.style.zIndex = '-1';
document.body.appendChild(_buffer);
}
var cs = window.getComputedStyle(textarea);
var pl = parseInt(cs.paddingLeft);
var pr = parseInt(cs.paddingRight);
var lh = parseInt(cs.lineHeight);
// [cs.lineHeight] may return 'normal', which means line height = font size.
if (isNaN(lh)) lh = parseInt(cs.fontSize);
// Copy content width.
_buffer.style.width = (textarea.clientWidth - pl - pr) + 'px';
// Copy text properties.
_buffer.style.font = cs.font;
_buffer.style.letterSpacing = cs.letterSpacing;
_buffer.style.whiteSpace = cs.whiteSpace;
_buffer.style.wordBreak = cs.wordBreak;
_buffer.style.wordSpacing = cs.wordSpacing;
_buffer.style.wordWrap = cs.wordWrap;
// Copy value.
_buffer.value = textarea.value;
var result = Math.floor(_buffer.scrollHeight / lh);
if (result == 0) result = 1;
return result;
}
Demo here
If I'm understanding the problem correctly, you need to count two things.
The number of hard line breaks "\n".
The number of lines that wrap past X characters.
Here's some pseudo code:
var lineLengthLimit = 40;
var lineCounter = 0;
foreach(lines as line){
lineCounter+=Math.floor(line.length/lineLengthLimit);
}
lineCounter += lines.length;
Another option might be what this guy suggested: https://stackoverflow.com/a/3697249/1207539 but it seems a bit sketchy.

Split String in Half By Word

I'm in a situation where I'd like to take a string and split it in half, respecting words so that this string here doesn't get split into this str ing here, rather it would be split into this string here.
I figure a starting step would to be to split the string into an array based on spaces, then calculate length based on those pieces, but in my attempts longer strings end up being split up incorrectly.
Look for the first space before and after the middle, and pick the one closest to the middle.
Example:
var s = "This is a long string";
var middle = Math.floor(s.length / 2);
var before = s.lastIndexOf(' ', middle);
var after = s.indexOf(' ', middle + 1);
if (middle - before < after - middle) {
middle = before;
} else {
middle = after;
}
var s1 = s.substr(0, middle);
var s2 = s.substr(middle + 1);
Demo: http://jsfiddle.net/7RNBu/
(This code assumes that there actually are spaces on both sides of the middle. You would also add checks for before and after being -1.)
Edit:
The check that I talked about in the node would be done correctly like this:
if (before == -1 || (after != -1 && middle - before >= after - middle)) {
middle = after;
} else {
middle = before;
}
Here is a fiddle where you can edit the text and see the result immediately: http://jsfiddle.net/Guffa/7RNBu/11/
I wanted to leave this as a comment but do not have enough rep points. The top solution right now fails pretty easily because it does not check for "-1" when using the indexOf method. See this fiddle:
http://jsfiddle.net/7RNBu/7/
var s = "This is a long strinjjjjjjjjjjjjjjjjg";
var middle = Math.floor(s.length / 2);
var before = s.lastIndexOf(' ', middle);
var after = s.indexOf(' ', middle + 1);
if (middle - before < after - middle) {
middle = before;
} else {
middle = after;
}
var s1 = s.substr(0, middle);
var s2 = s.substr(middle + 1);
You might also care about newlines, tabs, as well as spaces, so I would use a regex like this:
var s = "this string here";
var idx = s.length / 2;
while (idx < s.length && s[idx].match(/\s/) == null)
idx++;
var s1 = s.substring(0, idx);
var s2 = s.substring(idx);
document.getElementById("s1").innerText = s1;
document.getElementById("s2").innerText = s2;
See this fiddle: http://jsfiddle.net/nS6Bj/5/
let str = 'qwerty';
let half = Math.floor(str.length / 2);
str = str.slice(0, half) + ' ' + str.slice(half, str.length);
//output
'qwe rty'
I first thought I had an off-by-one error, but I eventually worked through it. Here's a working example.
Now to break down the logic used:
var calculate = function(initialString) {
var halfwayPoint = Math.floor(initialString.length / 2);
var strArray = initialString.split(' ');
// Caluclate halfway point, then break string into words
var wordFlag; // Will be split point
var charCount = 0;
_.each( strArray, function(word, strArrayIndex) {
if (wordFlag) return false;
// If we have the location, exit
// If charCount is before the halfway point
// and the end of word is after halfway point
// Then set the flag
// We add strArrayIndex to the word length to include spaces
if (charCount <= halfwayPoint &&
((charCount + word.length + strArrayIndex) >= halfwayPoint) ) {
wordFlag = strArrayIndex;
return false;
}
// Increase charCount to be length at the end of this word
charCount += (word.length);
});
if (!wordFlag) return null;
// Split the word array by the flag we figured out earlier
var lineOneArray = strArray.slice(0, (wordFlag + 1));
var lineTwoArray = strArray.slice(wordFlag + 1);
// We now join the word arrays into a string, stripping beginning and ending spaces.
var stOne = (lineOneArray.join(' ')).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var stTwo = (lineTwoArray.join(' ')).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
// Finally return the split strings as an array.
return [stOne, stTwo];
};
If anyone sees holes in my logic, let me know! I'm pretty sure this works in most cases though.
If you'd like the second string to be longer than the first, (ie have the line break before rather than after the middle word), then don't add +1 to wordFlag.
This will split your string based on word count (not character count, so the exact length of each half could be quite different, depending on the placement of long & short words).
var s = "This is a string of filler text";
var pieces = s.split(" "),
firstHalfLength = Math.round(pieces.length/2),
str1 = "",
str2 = "";
for (var i = 0; i < firstHalfLength; i++){
str1 += (i!=0?" ":"") + pieces[i];
}
for (var i = firstHalfLength; i < pieces.length; i++){
str2 += (i!=firstHalfLength?" ":"") + pieces[i];
}
document.write(s);
document.write("<br />"+str1);
document.write("<br />"+str2);
// Output
This is a string of filler text
This is a string
of filler text
http://jsfiddle.net/daCrosby/7RNBu/2/
<h1>
<span>
// for first half start from 0 till middle
{title.substring(0, title.length / 2)}
</span>
<span>
// second half just point the starting point
{title.substring(title.length / 2)}
</span>
</h1>

Categories

Resources