font size per language - javascript

One web page includes 3 different language words such as:
Language / 한국어 / ภาษาไทย
I'd like to enlarge Thai words(ภาษาไทย) in order to highlight it.
<span class="thai">ภาษาไทย</span>
Of course, it's possible if I specifiy 'class' property to all Thai sections, but it's too many to put them all.
If possible, I would like to change font-family & font-size according to unicode range with jquery.
Thank you.

You can use string.replace() to automatically tag every Thai word.
document.body.innerHTML = document.body.innerHTML.replace(
/([\u0E00-\u0E7F]+)/g,
function (x){return '<span class="thai">'+x+'</span>'}
);
See JSFiddle.

Although no JQuery, I would do something like this:
(In the case of Thai characters, they are in the Unicode range: 0E00-0E7F)
function StyleThaiInTag(tagName) {
var allTags = document.getElementsByTagName(tagName);
for (var i = 0; i < allTags.length; i++) {
var element = allTags[i];
var code = element.innerHTML.charCodeAt(0)
if (0x0E00 <= code && code <= 0x0E7F) {
// style element the way you want
element.style.fontSize = "2em";
//...
}
}
}
// example usage:
StyleThaiInTag('span');
StyleThaiInTag('div');
Here's a JSFiddle.

Related

How to create clozed text in HTML/CSS?

How can I cloze some text in an HTML document? Some marked text is hidden, replaced with an underline of exactly the same length as the original text and all of the words in the sentence should appear in precisely the same places they would appear had there not been a cloze. E.g.:
Once upon a time there ______ a cat.
The word to be clozed might be marked like this:
Once upon a time there <div class="cloze">lived</div> a cat.
Is there some way to hide the text and create an underline of exactly the same length?
Use some CSS:
.clozed {
border-bottom:1px solid black;
color:transparent;
}
This is <span class=clozed>text</span>.
Fiddle
Adding to #HoboSapiens answer (sorry, I can't comment due to score), you may also want to use the ::selection selector to ensure users can't drag across the area to uncover the text.
http://jsfiddle.net/Delorian/mm8tp1xb/
.clozed::selection {
color: transparent;
}
Note that users will always be able to see the text in the source, so if you want something more effective, you will need to use JavaScript on the client or server-side script to replace the text. However you will lose the benefit of having the underline at an accurate width.
You should do it via PHP, because if user would look into source code, he'll see the original text.
But if you need it in JS, you can implement it like this:
var spans = document.querySelectorAll('.clozed');
var words = [];
function repeat (str, count) {
var text = '';
var i;
for (i = 0; i < count; i++) {
text += str;
}
return text;
}
var i, c = spans.length;
for (i = 0; i < c; i++) {
var span = spans[i];
var text = span.innerText = span.textContent;
words.push(text);
span.innerText = span.textContent = repeat('_', text.length);
}
http://jsfiddle.net/0e7hw2a9/
Note: you may use words array to validate the input later.
Update: undo function: http://jsfiddle.net/0e7hw2a9/2/

Markdown to convert double asterisks to bold text in javascript

i'm trying to make my own markdown-able textarea like Stackoverflow has done. The goal is to allow people to type **blah blah** in a textarea and have the output in a div be <span style="font-weight:bold;">blah blah</span>.
I'm having trouble with the javascript to find and replace to the **asterisks with the HTML.
here's a jsfiddle which has gotten the party started: http://jsfiddle.net/trpeters1/2LAL4/14/
here's the JS on that just to show you where I'm at:
$(document.body).on('click', 'button', function() {
var val=$('textarea').val();
var bolded=val.replace(/\**[A-z][0-9]**/gi, '<span style="font-weight:bold;">"'+val+'" </span>');
$('div').html(bolded);
});
and the HTML...
<textarea></textarea>
<div></div><button type="button">Markdownify</button>
any thoughts would be greatly appreciated!
thanks,
tim
The other answers fail when a char is immediately before or after the asterisks.
This works like markdown should:
function bold(text){
var bold = /\*\*(.*?)\*\*/gm;
var html = text.replace(bold, '<strong>$1</strong>');
return html;
}
var result = bold('normal**bold**normal **b** n.');
document.getElementById("output").innerHTML = result;
div { color: #aaa; }
strong { color: #000; }
<div id="output"></div>
None of the provided answers works in all cases. For example, the other solutions wont work if we have a space next to the double star, ie:
This will ** not ** be bold
So I wrote this:
function markuptext(text,identifier,htmltag)
{
var array = text.split(identifier);
var previous = "";
var previous_i;
for (i = 0; i < array.length; i++) {
if (i % 2)
{
//odd number
}
else if (i!=0)
{
previous_i = eval(i-1);
array[previous_i] = "<"+htmltag+">"+previous+"</"+htmltag+">";
}
previous = array[i];
}
var newtext = "";
for (i = 0; i < array.length; i++) {
newtext += array[i];
}
return newtext;
}
Just call it like this:
thetext = markuptext(thetext,"**","strong");
and it will work in all cases. Of course, you can also use it with other identifiers/html-tags as you like
(the stackoverflow preview should have this too).
Choose the perfect regex that will fit your needs.
If you don't want styling to span through new line and also using ([^*<\n]+) makes sure at least one character is in between styles or else ** without a character in-between will result will become invisible.
function format_text(text){
return text.replace(/(?:\*)([^*<\n]+)(?:\*)/g, "<strong>$1</strong>")
.replace(/(?:_)([^_<\n]+)(?:_)/g, "<i>$1</i>")
.replace(/(?:~)([^~<\n]+)(?:~)/g, "<s>$1</s>")
.replace(/(?:```)([^```<\n]+)(?:```)/g, "<tt>$1</tt>")
}
•The downside to the above code is that, you can't nest styles i.e *_Bold and italic_*
To allow nested styles use this 👇
format_text(text){
return text.replace(/(?:\*)(?:(?!\s))((?:(?!\*|\n).)+)(?:\*)/g,'<b>$1</b>')
.replace(/(?:_)(?:(?!\s))((?:(?!\n|_).)+)(?:_)/g,'<i>$1</i>')
.replace(/(?:~)(?:(?!\s))((?:(?!\n|~).)+)(?:~)/g,'<s>$1</s>')
.replace(/(?:--)(?:(?!\s))((?:(?!\n|--).)+)(?:--)/g,'<u>$1</u>')
.replace(/(?:```)(?:(?!\s))((?:(?!\n|```).)+)(?:```)/g,'<tt>$1</tt>');
// extra:
// --For underlined text--
// ```Monospace font```
}
👆 If you want your style to span through new line, then remove \n from the regex. Also if your new line is html break tag, you can replace \n with <br>
Thank me later!
Why create from scratch? With so many open source editors out there, you should pick a code base you like & go from there.
http://oscargodson.github.com/EpicEditor/
http://markitup.jaysalvat.com/home/
custom component in react who receives bold like boolean
{(() => {
const splitText = theText.split('**');
return (
<TextByScale>
{splitText.map((text, i) => (
<TextByScale bold={!!(i % 2)}>{text}</TextByScale>
))}
</TextByScale>
);
})()}
If you are using jQuery, replace this:
$(document.body).on('click', 'button', function() {
with this:
$("button").click(function () {
The following regular expression will find your asterisk-wrapped text:
/\x2a\x2a[A-z0-9]+\x2a\x2a/
I updated your fiddle as an example: http://jsfiddle.net/2LAL4/30/
Your regex is broken, for one thing. You probably want something more like:
/\*\*[A-z0-9]+\*\*/gi
The * is a special character in regular expressions. If you want to match against a literal *, then you need to escape it with \.
For instance: http://jsfiddle.net/2LAL4/22/
However, even with this change there's still a fair ways to go before you get to where you really want to be. For instance, your example will not work if the text area contains a mix of bold and non-bold text.

Replace too long strings with "..."

Lets say we have a <div style="width:100px;">This text is too long to fit</div>
The text in the div is dynamic. And I'd like to force the text to fit in width and not break.
So i need some kind of functionality to test if the text is going to fit, and if it is not, then i'd like to display the portion of the text that will actually fit. And append ...to the end.
Result for a too long text should be something like this: "This text is..."
Is there some standard way of doing what i want? Either by javascript, jquery, jsp or java?
Thanks!
Edit:
Thanks for your quick and many answers! I was doing this in java by guessing how many characters would fit. It seemed like a less than optimal solution, so thats why i came here.
The css solution is perfect for me. Its not that big of a deal that it doesnt work for firefox, since my clients all use ie anyway. :)
you could do it with css3 using text-overflow:ellipsis http://www.css3.com/css-text-overflow/
or if you insist on using the js way, you can wrap the text-node inside your div and then compare the width of the wrap with the with of the parent.
If you want to process the data you can use a function:
function TextAbstract(text, length) {
if (text == null) {
return "";
}
if (text.length <= length) {
return text;
}
text = text.substring(0, length);
last = text.lastIndexOf(" ");
text = text.substring(0, last);
return text + "...";
}
text = "I am not the shortest string of a short lenth with all these cows in here cows cows cows cows";
alert(TextAbstract(text,20));
EDIT: process all div with excess length in the text:
var maxlengthwanted=20;
$('div').each(function(){
if ($('div').text().length > maxlengthwanted)
$(this).text(TextAbstract($(this).text()));
});
EDIT: More compact version to process all div with excess length in the text, breaks on space.
function textAbstract(el, maxlength = 20, delimiter = " ") {
let txt = $(el).text();
if (el == null) {
return "";
}
if (txt.length <= maxlength) {
return txt;
}
let t = txt.substring(0, maxlength);
let re = /\s+\S*$/;
let m = re.exec(t);
t = t.substring(0, m.index);
return t + "...";
}
var maxlengthwanted = 23;
$('.makeshort').each(function(index, element) {
$(element).text(textAbstract(element, maxlengthwanted, " "));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="makeshort">This is a fun thing to process, modification of this is going to just be soo much fun</div>
<div class="makeshort">second This is a fun thing to process, modification of this is going to just be soo much fun</div>
<div class="makeshort">IBShort Wilson</div>
<div class="makeshort">another This is a fun thing to process, modification of this is going to just be soo much fun</div>
<div class="makeshort">more This is a fun thing to process, modification of this is going to just be soo much fun</div>
<span class="makeshort">Me also, a span that is a fun thing to process, modification of this is going to just be soo much fun</span>
<span class="makeshort">more This is a fun thing to process, modification of this is going to just be soo much fun</span>
<ul>
<li class="makeshort">li1 more This is a fun thing to process, modification of this is going to just be soo much fun</li>
<li class="makeshort">li 2 more This
is a
fun thing to process, modification of this is going to just be soo much fun</li>
<li class="makeshort">li 3 also moreThis is a fun thing to process, modification of this is going to just be soo much fun</li>
<li class="makeshort">li 4 also more This is fun thing to process, modification of this is going to just be soo much fun</li>
</ul>
if(text.length > number_of_characters) {
text = text.substring(from, to);
}
One liner using JavaScript
The below truncates the string to 10 characters with an ellipsis. If the length of the truncated string is below the limit (10 in the example below) then no ellipsis is added to the output.
const output = "abcdefghijk".split('', 10).reduce((o, c) => o.length === 9 ? `${o}${c}...` : `${o}${c}` , '');
Easiest way to shorten the variable using JavaScript:
function truncate(string, length){
if (string.length > length)
return string.substring(0,length)+'...';
else
return string;
};
Inspired by this answer: I want to truncate a text or line with ellipsis using JavaScript
If the string is a one-liner you can use the CSS solution. If its a multiline string you need to clip, i prefer using a lightweight JS plugin called cuttr.js.
Just a minimum of code needed to get it done. You could even omit the endingoption, because the three dots are the default output.
Vanilla JS implementation:
new Cuttr('.selector', {
length: 15,
ending: '...'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/cuttr/1.3.2/cuttr.min.js"></script>
<div class="selector" style="width:100px;">This text is too long to fit</div>
jQuery implementation:
$('.selector').Cuttr({
length: 15,
ending: '...'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cuttr/1.3.2/cuttr.min.js"></script>
<div class="selector" style="width:100px;">This text is too long to fit</div>
Simply add a class to the div and init the plugin. You can read more about truncating a text or line with ellipsis on the plugins website or github page - there are multiple ways to clip the string, even without messing up HTML tags.
text-overflow: ellipis
div {
text-overflow: ellipsis
}
Will be supported in FireFox 7 http://caniuse.com/#search=text-overflow
If you add an id tag to the div, you can use document.getElementById("divid").innerHTML to get the contents of the div. From there, you can use .length to get the length of the string. If the length of the string is over a certain threshold, just take a substring and append a "...".
You should try to do this server-side if you can, though. Relying on Javascript/CSS to format it correctly for the user is a less than ideal solution.
Try the CSS text-overflow property.
A more likely situation is that you can't possibly know how many characters are going to fit in a dom element, given it has its own font and so on. CSS3 is not currently an option (for me anyway). So, I create a little div offscreen and keep jamming test strings into it until the width is correct:
var text = 'Try to fit this text into 100 pixels!';
var max_width = 100;
var test = document.createElement('div');
test.className = 'Same Class as your real element'; // give it the same font, etc as a normal button
test.style.width = 'auto';
test.style.position = 'absolute';
test.style.left = '-2000px';
document.body.appendChild(test);
test.innerHTML = text;
if ($(test).width() > max_width) {
for (var i=text.length; i >= 0; i--) {
test.innerHTML = text.substring(0, i) + '...';
if ($(test).width() <= max_width) {
text = text.substring(0, i) + '...';
break;
}
}
}
document.body.removeChild(test);

Javascript - Link Name Changing with restrictions

I'm trying to change the name of a link, however, I have some restrictions. The link is placed in code that looks like this:
<li class='time'>
Review Time
<img alt="Styled" src="blah" />
</li>
Basically, I have a class name to work with. I'm not allowed to edit anything in these lines, and I only have a header/footer to write Javascript / CSS in. I'm trying to get Review Time to show up as Time Review, for example.
I know that I can hide it by using .time{ display: hide} in CSS, but I can't figure out a way to replace the text. The text is also a link, as shown. I've tried a variety of replace functions and such in JS, but I'm either doing it wrong, or it doesn't work.
Any help would be appreciated.
You could get the child elements of the li that has the class name you are looking for, and then change the innerHTML of the anchor tags that you find.
For example:
var elements = document.getElementsByClassName("time")[0].getElementsByTagName("a");
for(var i = 0, j = elements.length; i<j; i++){
elements[i].innerHTML = "Time Review";
}
Of course, this assumes that there is one element named "time" on the page. You would also need to be careful about checking for nulls.
Split the words on space, reverse the order, put back together.
var j = $('li.time > a');
var t = j.text();
var a = t.split(' ');
var r = a.reverse();
j.text(r.join(' '));
This could have some nasty consequences in a multilingual situation.
Old school JavaScript:
function replaceLinkText(className, newContents) {
var items = document.getElementsByTagName('LI');
for (var i=0; i<items.length; i++) {
if (items[i].className == className) {
var a = items[i].getElementsByTagName('A');
if (a[0]) a[0].innerHTML = newContents;
}
}
}
replaceLinkText("time", "Review Time");
Note that modern browsers support getElementsByClassName(), which could simplify things a bit.
You can traverse the DOM and modify the Text with the following JavaScript:
var li = document.getElementsByClassName('time');
for (var i = 0; i < li.length; i++) {
li[i].getElementsByTagName('a')[0].innerText = 'new text';
}
Demo: http://jsfiddle.net/KFA58/

Implementing Show More - Show Less text on a page

I have a content oriented product. And at one point I display a list of available entities, with their full summary. Now, the said summary is the data entered by user using TinyMCE editor (i.e. it can contain HTML tags like img, p, span, ul, li, etc.). As summary can span a few hundred lines, I want to cleanly implement the Show More-Less feature, using javascript where I load the summary hidden partially by default, and show rest only when user click, 'Show More'.
It would be great to know, how you guys have or would have implemented it. I am thinking to limit the variety of markup entered by user and use regex to split the markup with a span link to load-more (much like facebook does it).
Note: I cannot split the text according to number of characters/words, as it can violate markup. I cannot hide the content by limiting height due to img tags (which loads later and can alter the height of containing div, and in-turn spoil your height calculations.)
http://henrik.nyh.se/2008/02/jquery-html-truncate A very neat implementation by this guy.
You can also see working demonstration here http://henrik.nyh.se/examples/truncator/
I would use the following function to get rid of unwanted html tags.
// Strips HTML and PHP tags from a string
// returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
// example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
// returns 2: '<p>Kevin van Zonneveld</p>'
// example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
// returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
// example 4: strip_tags('1 < 5 5 > 1');
// returns 4: '1 < 5 5 > 1'
function strip_tags (str, allowed_tags)
{
var key = '', allowed = false;
var matches = []; var allowed_array = [];
var allowed_tag = '';
var i = 0;
var k = '';
var html = '';
var replacer = function (search, replace, str) {
return str.split(search).join(replace);
};
// Build allowes tags associative array
if (allowed_tags) {
allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
}
str += '';
// Match tags
matches = str.match(/(<\/?[\S][^>]*>)/gi);
// Go through all HTML tags
for (key in matches) {
if (isNaN(key)) {
// IE7 Hack
continue;
}
// Save HTML tag
html = matches[key].toString();
// Is tag not in allowed list? Remove from str!
allowed = false;
// Go through all allowed tags
for (k in allowed_array) { // Init
allowed_tag = allowed_array[k];
i = -1;
if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag) ;}
// Determine
if (i == 0) { allowed = true;
break;
}
}
if (!allowed) {
str = replacer(html, "", str); // Custom replace. No regexing
}
}
return str;
}
Usage if content is the editor content. This will keep Spans:
var my_clean_content = strip_tags( content, 'span');
Personally, I'd do this with jQuery and use a plugin such as Text Constrain.
You can download it here, or view other similar plugins on the jQuery site.
The best jQuery plugin I've seen that implements this functionality is Expander. It's also got the advantage of having been around for several years and is still actively maintained as of the time this was written unlike most or all of the other solutions linked to in answers to this question.

Categories