Can you force a string to split into 'n' lines? - javascript

On a website I'm designing, I have a page with rows of categories thumbnails and their titles.
The problem is : some category titles are long, other are shorts... depending on the monitor width some will take 2 lines of text, or even 3, but not the others, creating ugly staircases.
I've managed to identify the highest title and min-height every other one accordingly with javascript.
But, it's still ugly. To make it better, I'd want every title to break into as many lines than the longest one.
That's where I come short... I couldn't find a way to do that so far.
Here's how it is now :
Here's the intended result :
Any idea how I could accomplish this ?

If you want to do that with a javascript solution you can count characters or words and add <br> after n amount. Here is a sample that will add a line break after every 20 characters:
var string = document.getElementById('text');
string.innerHTML = string.textContent.replace(/(.{20})/g, "$1<be>");
Then you can create a function with a loop for each element and do some if statement logic there. For example - add a break if the character count is more than...

Related

Dynamically splitting an array depending on character count

I have an array like so:
const testArray = [ 'blah', 'abc​testtt​​', 'atestc​', 'testttttt' ]
I would like to split the string once it reaches a certain character count, for example lets use 10 characters. Also, I would like the output to swap itself to be able to use within 10 characters. Please see the expected output below if this doesn't really make sense to you. Please assume that each item in the array will not be above 10 characters just for example purpose.
So once the testArray reaches 10 characters I would like the next item to be under a new variable maybe? Not sure if thats the best way of doing this.
Something like this maybe? Again this may be very inefficient, if so please feel free to use another method.
const testArray = [ 'blah', 'abctesttt​​', 'atestc', 'testttttt' ]
if ((testArray.join('\n')).length) >= 10 {
/* split the string into parts and store it under a variable maybe?
console.log((the_splitted_testArray).join('\n')); */
}
Expected output:
"blah
atestc" //instead of using "abctesttt" it would use "atestc" as it's the next element in the array and it also avoids reaching the 10 character limit, if adding "atestc" caused the character limit to go over 10, I would like it to check the next element and so on
"abctesttt" // it can't add the remaining "testttttt" since that would cause the character limit to be reached
"testttttt"
First of all, as you can't create a new variable out of nowhere at run time, you are probably going to use a "parent"-array, which then contains the actual strings with a length of 10 maximally.
For the grouping you probably have to design an algorithm yourself. My first idea for an algorithm is something like below. Probably not the best and most efficient way (as the description of "efficient" depends on your personal priorities), but feel free to optimise it yourself :)
Walk through $testArray[], sort all strings into a new two-dimensional array: $stringLength[$messagesWithSameLength[]]. Like array(1=>array('.','a'),2=>array('hi','##',...),...)
Now, always try to get as many strings together as possible. Start with one of the longest strings, calculate the remaining space and get a string suiting best into it. If none fits, start a new group.
Always try to use the space as good as possible

Split Long Filename string in two Lines with Adobe Javascript

I am newbie using Javascript in Adobe. I have written script that catch the file name and add it as a title in the document, but problem is it doesn't split in 2 lines long file names. So long text file names are out of the page border.
For example file name is
"This is a text that I need to split in two lines How to write the script in order to split the long text and fit in the page"
This is just a sample. What I need to edit? And is it possible?
var trFileName = this.documentFileName.replace(/.*\/|\.pdf$/ig,""); //remove .pdf extension
var pageAmount = this.numPages; //define how many pages are there
this.addWatermarkFromText({
cText: trFileName,
nStart: 0,
nEnd: pageAmount,
nFontSize: 18,
aColor: color.blue,
cFont: "Helvetica-Bold",
nTextAlign: app.constants.align.center,
nHorizAlign: app.constants.align.center,
nVertAlign: app.constants.align.top,
//nHorizValue: -25,
nVertValue: -87.87
})
So looking at the documentation for Acrobat the quick way to do this is to add and use the bPercentage: -1 property which ought to scale the watermark to fit the page with a max of 100%. Obviously, the longer the text, the smaller the the typesize, but it ought to only scale when needed.
The big problem here is "how big is too big?" Since most fonts are not fixed-width. So if you do not have some function to check the size of the type in that font, you would need to set up a temp image, set the type, then measure the dimensions of the image, then decide how much to break the text.
The worst case for English though is probably going to be an endless string of W, so if you want to hard code the font size and some reasonable character limit, you can get a reasonable max character count by counting how many Ws it takes to go out of bounds.
Once you have that number you can split the string.
One way to split a string is to use substring:
var cDisplayText = trFilename;
var nMaxChars = 10;
var cAdobeNewline = '\r';
var cLineBreakChar = '-';
if (cDisplayText.length > nMaxChars && cDisplayText.length > 0) {
cDisplayText = cDisplayText.substring(0, nMaxChars)
+ cLineBreakChar
+ cAdobeNewline
+ cDisplayText.substring(nMaxChars);
}
And then replace cText: trFileName, with cText: cDisplayText,
I have not tested this and my javascript has atrophied a little, but the idea is to test the string length and insert a hyphen and a line break.
This (obviously) does not account for case where there is more than 1 line break required.

Select random combinations of list elements such that no list element is present in more than one selection (SQL)

I'm running a bit out of ideas how to realize a small project.
What I have:
- a list of users including their ID and name
What I want to achieve:
- I want to combine each user on this list with another user such that no user is assigned to more than one user and no user is assigned to herself.
- The combination has to be random and has to take past combinations into account
My idea so far:
- I have this information:
User (A,B,C,D) (the actual number of users ranges between 50 and 400)
Possible combinations: (A-B,A-C,A-D,B-C,B-D,C-D)
Random draw(1): (A-B, C-D)
Random draw(2): (A-D, B-C)
Random draw(3): (A-C, B-D)
I was able to get all possible combinations using a join of the user table with itself.
I guess I can take previous draws into account by storing the draws in a separate table and limit the possible combinations to those that are not in this special table.
What I can't do:
- I don't know how to randomly draw from the list of possible combinations such that every user is part of only one combination per draw (e.g. A-B,A-D in the same draw is not allowed)
- I try to use sql or a bit php for this (maybe javascript)
Thanks for any help.
An easy solution:
Create a temporary table with a row for each pairing. Loop over the list of users skipping a random number of empty rows from 1 to the number of empty rows -- insert user.
Easy solution number 2:
Given N users. Assign each user a unique random number from 1 to N (remove randomly from the set of all numbers from 1 to N). Pair each user with from 1-N/2 with user from N/2+1 to N.
The solution is the problem "Bergr (s) table", see Wikipedia: http://en.wikipedia.org/wiki/Round-robin_tournament.
The latest (best) solution is from Professor Frončeka (Dalibor Froncek, a professor at the University of Minnesota in the US).
For custom solutions, look in the table of solutions n ^ 2.

Can i generate unique text 1 lacs time in javascript through any method who does not need any framework?

i have a word from A to Z. all word should in small latter (Capital not include) and 1 to 9 (included all special word who can be used in email address (just for a test)).
how i can generate unique 1 lacs text who never repeat itself. can anyone solve this puzzle.
i want a another thing that all words should not more then 10 char and not should minimum 6 char long
Put the characters in an array. Copy the array as the source of a new line. Randomly slice words from the array and put them in the line (use Math.random() * array.length | 0). Keep going for the required number of words.
You can also just use a string and charAt(index) if you only want single characters, but you have to keep cutting out the character that you select which is likely less efficient than using array.slice.
Whatever suits though, since performance is likely irrelevant.

word decoder by javascript?

Implement the “Word Decoder” game. This game will present the player with a series of scrambled words (up to 20 words) and challenge him/her to attempt to unscramble them. Each time a new word is displayed, and a text input is provided for the user to write the unscrambled word.
Once the player thinks the word has been properly decoded, he clicks on the “Check answer” button. If the player’s answer is correct, his score is increased by one. If his answer is not correct, he is notified and he is then given a different word.
i understood the Question , but i dont know how to generate it , or even how to start it!!
any help please?
To start, try breaking down the problem into things you'll need; think nouns and verbs. This is simply rewriting the problem in new terms. You need:
word: just a string, but it's a noun you'll need, so list it.
dictionary: a collection of words to choose from (during testing, you don't need many)
display: these become HTML elements, since you're working with JS
scrambled word
text input
submit button to check answer
score
"wrong answer" notifier
to scramble a word
to compare words: how can you compare two words to see if one is a permutation of the other? Do it right and anagrams aren't a problem.
to check an answer
to increment score
to notify user of incorrect answer
to present a new scrambled word
Any item beginning with "to" is a verb; anything else is a noun. Nouns become objects, verbs become methods/functions.
The above is mostly a top-down approach, in contrast with bottom-up (note that top-down vs bottom-up isn't an either-or proposition). Other approaches that might help with not knowing where to start are test driven development or its offshoot, behavior driven development. With these you start by defining, in code, what the program should do, then fill in the details to make it do that.
A hint on comparing words: the problem is basically defining an equivalence class—two strings are equivalent if one is a permutation of the other. The permutations of a string, taken together, form the equivalence class for that string; two strings are in the same equivalence class if the strings are equivalent. As the linked document points out, equivalence classes are well represented by picking a single element of the class as the class representative. Lastly, you can turn the equivalence class definition around: two strings are permutations of each other if they are in the same equivalence class.
Look into loading a dictionary via XHR.
there are tons of those available online [http://www.mieliestronk.com/wordlist.html NOTE: it contains some swear words, if you're going to be doing this for academic purposes, since its your homework, you should look for a "clean" list]...
For scrambling the word: make your string into a char array, then find an array shuffle function [they are simple to write, I wrote one for my implementation of Bogosort]...
function shuffle(b)
{
var a = b.concat([]); //makes a copy of B, b won't be changed...
var final = [];
while(a.length != 0)
{
//0 -> a length-1
var targIndex = Math.round((a.length-1)*(Math.random()));
var value = a[targIndex]
a.remove(targIndex);
final.push(value);
}
return final;
}
When the user is done inputting, simply compare input with the answer [case insensitive, ignore spaces] As stated in comments, there are also the possibility of anagrams, so be sure to check for those... perhaps, you could simply verify the word exists in the dictionary.

Categories

Resources