How to break a sentence into different parts in css - css

I want to break a sentence in 3 parts using css, e.g., United States ("US") - Tax reforms
Here I want to name 3 parts from the sentence.
name: United States
symbol: US
subject: Tax reforms
I know I can use (" to yield name, (" and ") to yield symbol, and ") - to yield subject. But I don't know how to.
I looked up on "word-break" but it doesn't seem to achieve what I want.

You cannot use CSS for splitting a string into parts. You simply cannot target single letters with CSS (except for the first letter with the :first-letter pseudo class). See also this question for more information on this subject.
You could use JavaScript combined with e.g. a regular expression. A simple example would be the following (just as a reminder: do not parse user-content directly as HTML for security reasons):
const input = 'United States ("US") - Tax reforms';
const regex = /^([\w\s]+)\s\("(\w+)"\)\s-\s([\w ]+)/;
const result = regex.exec(input);
if (result !== null) {
const resultingObject = {
name: result[1],
symbol: result[2],
subject: result[3]
};
console.log(resultingObject);
document.body.innerHTML = `<p class="name">${resultingObject.name}</p>
<p class="symbol">${resultingObject.symbol}</p>
<p class="subject">${resultingObject.subject}</p>`;
}
.name {
font-weight: bold;
}
.symbol {
font-style: italic;
}
.subject {
text-decoration: underline;
}

Related

Can I use Chinese characters in CSS class names?

Is it possible to use Chinese class names for my CSS classes? I'm trying to get the Chinese word with jQuery and then create img elements with classes named by the Chinese words.
I have for instance a file named 2020_Cars_哈喽_1.jpg, and I created a code that takes the year, the category (Cars), and the Chinese word which is the name of the album, and creates an img element with classes according to the file name in order to filter the images later.
I have an example here where you can see the categories which translated to classes without any problem, and the %46%bd% which are Chinese words that I could not transform successfully into a class name.
Any suggestions please?
The jQuery code which takes the file name and split it into classes:
$.ajax({
url: dir,
success: function(data){
$(data).find("a:contains(.JPG)").each(function(){
// will loop through
var images = $(this).attr("href");
var splittedName = images.split('_');
var classesToAdd = 'thumbnailpic';
for(var i=0;i<3;i++){
classesToAdd+=' '+splittedName[i];
}
if(years.indexOf(splittedName[0])===-1){
years.push(splittedName[0]);
}
if(categories.indexOf(splittedName[1])===-1) {
categories.push(splittedName[1]);
}
if(albums.indexOf(splittedName[2])===-1) {
albums.push(splittedName[2]);
}
$('.gallery').append('<img class="'+classesToAdd+'" src="'+dir+'/'+images+'"'+'>');
});
for(var a=0;a<years.length;a++){
$('.years').append('<div id="filter-button" class="filter-select" >'+years[a]+'</div>');
}
for(var b=0;b<categories.length;b++){
$('.categories').append('<div id="filter-button" class="filter-select">'+categories[b]+'</div>');
}
for(var c=0;c<albums.length;c++){
$('.albums').append('<div id="filter-button" class="filter-select">'+albums[c]+'</div>');
}
hideBigPic();
$('.filters').fadeIn(1000);
$('.gallery').fadeIn(1000);
}
});
Thank you in advance!
Yes, you can use Chinese characters as class names and selectors.
div {
width: 100px;
height: 100px;
}
.tomato {
background: tomato;
}
.蓝色 {
background: navy;
}
<div class="蓝色"></div>
<div class="tomato"></div>
<br>
<button onclick="console.log(document.querySelector('.蓝色'))">Find Element</button>
But it looks like the real question here is how do you turn URL encoded characters (%46 etc) back into real characters and for that you need decodeURIComponent
console.log(decodeURIComponent('%E8%93%9D'))
Hope this answers all of your questions.

Fake capitalization on an all-caps font with CSS?

Is it possible to fake lowercase letters on a font that has only one letter type, which is ALL CAPS?
This is a sentence on Stack Overflow.
Looks like this when the font is applied:
THIS IS A SENTENCE ON STACK OVERFLOW.
I want the capitals to be a slightly larger font size as in the example below. But without the additional HTML markup.
body {
font-family: Arial, sans-serif;
font-size: 12px;
}
span {
font-size: 1.4em;
}
<span>T</span>HIS IS A SENTENCE ON <span>S</span>TACK <span>O</span>VERFLOW
I'd say the best way to achieve this is with JavaScript (so you could keep the markup dynamic). The JS part that you'd need is this (remember to add .small-caps class to your text elements):
function smallCaps() {
var elements = document.querySelectorAll('.small-caps')
Array.prototype.forEach.call(elements, function(e) {
var text = e.innerHTML.toUpperCase()
e.innerHTML = text.replace(/\b([A-Za-z0-9])/g, '<span class="caps">$1</span>')
})
}
And also remember to add styles for the .caps class:
.caps {
font-size: 1.4em;
}
See it in action either in a fiddle or below:
smallCaps()
// This is what you need:
function smallCaps() {
var elements = document.querySelectorAll('.small-caps')
Array.prototype.forEach.call(elements, function(e) {
var text = e.innerHTML.toUpperCase()
e.innerHTML = text.replace(/\b([A-Za-z0-9])/g, '<span class="caps">$1</span>')
})
}
.caps {
font-size: 1.4em;
}
<h1 class="small-caps">HELLO WORLD</h1>
<h2 class="small-caps">Nifty FOOBAR title</h2>
Sentence case in font-variant: small-caps. The titleCase() function works perfectly with the letters wrapped in <span>s.
I want the capitals to be a slightly larger font size as in the example below. But without the additional HTML markup.
The first 4 comments on OP are correct. I'd like to reaffirm #Pete's comment:
css can only target the first letter or word in a sentence, other than that you will need extra html otherwise how would css know you want the first letter and then the s of stack and o of overflow?
Thus, you will get answers of every variety and each successful answer will have markup in some form or another. With JavaScript, you could have a range determined by a whitelist/dictionary but covering any range of proper nouns would be very limited. Capabilities of that magnitude should be possible with a language like Python, Java, C/C++, etc.
Demo
var main = document.body;
var text = main.textContent;
titleCase(text);
main.style.fontVariant = 'smallCaps';
function titleCase(str) {
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
body {
font-family: Arial, sans-serif;
font-size: 12px;
}
span {
font-size: 1.4em;
}
<span>T</span>HIS IS A SENTENCE ON <span>S</span>TACK <span>O</span>VERFLOW

Style an ordered list with Cyrillic letters

There are many possible values for list-style-type CSS property (e. g. decimal, lower-latin, upper-greek and so on). However there are none for the Cyrillic alphabet (which, btw, has different variations for different languages).
What is the best way to style an ordered list with Cyrillic letters?
(I'm providing a solution I ended up with despite I'm not very happy with it.)
I know nothing about Cyrillic list schemes so I’m at risk of a bit of cultural embarrassment here, but CSS3 Lists module (still in working draft) defines quite a few Cyrillic alphabetic list types: lower-belorussian, lower-bulgarian, lower-macedonian, lower-russian, lower-russian-full, lower-serbo-croatian, lower-ukrainian, lower-ukrainian-full, upper-belorussian, upper-bulgarian, upper-macedonian, upper-russian, upper-russian-full, upper-serbo-croatian, upper-ukrainian, upper-ukrainian-full. As expected, the state of support for these is deplorable currently (certainly nothing in Gecko or WebKit), but hopefully going forwards these will start to be implemented.
Update: some changes have been made – the definition of list types has been moved into the CSS3 Counter Styles module whose current draft (Feb 2015) has unfortunately lost all alphabetical Cyrillic types. This is in Candidate Recommendation stage so it’s unlikely that additions will be made at the point. Perhaps in CSS4 List Styles?
In this method I'm using CSS-generated content in before each list item.
.lower-ukrainian {
list-style-type: none;
}
.lower-ukrainian li:before {
display: inline-block;
margin-left: -1.5em;
margin-right: .55em;
text-align: right;
width: .95em;
}
.lower-ukrainian li:first-child:before {
content: "а.";
}
.lower-ukrainian li:nth-child(2):before {
content: "б.";
}
/* and so on */
Disadvantages
Hardcoded, restrict list to a certain max length.
Not pixel-perfect as compared to a regular order list
Here is another solution for Cyrillic letters with pretty clear code: jsfiddle.net
(() => {
const selector = 'ol.cyrillic',
style = document.createElement('style');
document.head.appendChild( style );
'абвгдежзиклмнопрстуфхцчшщэюя'.split('').forEach((c, i) =>
style.sheet.insertRule(
`${selector} > li:nth-child(${i+1})::before {
content: "${c})"
}`, 0)
);
})();
PS. You can convert this next-gen code to old one with Babel: babeljs.io
I'm surprised that there is no Cyrillic numbering. Here's a quick JS solution for you:
function base_convert(n, base) {
var dictionary = '0123456789abcdefghijklmnopqrstuvwxyz';
var m = n.toString(base);
var digits = [];
for (var i = 0; i < m.length; i++) {
digits.push(dictionary.indexOf(m.charAt(i)) - 1);
}
return digits;
}
var letters = {
'russian': {
'lower': 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя',
'upper': 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
}
}
$('ul, ol').each(function() {
if (!(results = $(this).prop('class').match(/(upper|lower)-([a-z]+)/i))) return;
var characters = letters[results[2]][results[1]];
$('> li', this).each(function(index, element) {
var number = '', converted = base_convert(++index, characters.length);
for (var i = 0; i < converted.length; i++) {
number += characters.charAt(converted[i]);
}
$(this).attr('data-letter', number);
});
});​
My written Russian is admittedly bad, as you can see by my inability to count with letters, so change the letters object appropriately.
Demo: http://jsfiddle.net/JFFqn/14/

First lowercase the text then capitalize it. Is it possible with CSS?

First lowercase the text then capitalize it. Is it possible with CSS?
Edit: Example:
HELLO WORLD -> Hello World
Edit2: I have a list of countries which are all uppercase, like UNITED KINGDOM, I have to make it look like United Kingdom.
Yep:
.className {
text-transform:capitalize;
}
Javascript:
function capitalize(s){
return s.toLowerCase().replace( /\b./g, function(a){ return a.toUpperCase(); } );
};
capitalize('this IS THE wOrst string eVeR');
Stolen from here:
Capitalize words in string
This can be done if the text inside the element is only on one line, using the ::first-line pseudo-element:
<h3>HELLO WORLD</h3>
<style>
h3 {
text-transform: lowercase;
}
h3::first-line {
text-transform: capitalize;
}
</style>
I not have permission to comment, so I'll write my experience as an answer.
I have a problem with accentuated chars, solved puting '^' in the begin of regex and iterate each word of the text.
'^' indicates to match only the first char of word.
function captalize(s) {
return s.toLowerCase().replace( /^\b./g, function(a){ return a.toUpperCase(); } );
}
var words = exampleText.split(" ");
jQuery.each(words, function(index, value) {
var w = capitalize(value);
exampleText.append(w).append(" ");
});
The best solution for me was to apply .toLocaleLowerCase() in Javascript and then use the CSS text-transform: capitalize;.
This way, all the first letters are uppercase. I wish we could achieve that with pure CSS only.

CSS text-transform capitalize on all caps

Here is my HTML:
small caps &
ALL CAPS
Here is my CSS:
.link {text-transform: capitalize;}
The output is:
Small Caps & ALL CAPS
and I want the output to be:
Small Caps & All Caps
Any ideas?
You can almost do it with:
.link {
text-transform: lowercase;
}
.link:first-letter,
.link:first-line {
text-transform: uppercase;
}
It will give you the output:
Small Caps
All Caps
There is no way to do this with CSS, you could use PHP or Javascript for this.
PHP example:
$text = "ALL CAPS";
$text = ucwords(strtolower($text)); // All Caps
jQuery example (it's a plugin now!):
// Uppercase every first letter of a word
jQuery.fn.ucwords = function() {
return this.each(function(){
var val = $(this).text(), newVal = '';
val = val.split(' ');
for(var c=0; c < val.length; c++) {
newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length) + (c+1==val.length ? '' : ' ');
}
$(this).text(newVal);
});
}
$('a.link').ucwords();​
Convert with JavaScript using .toLowerCase() and capitalize would do the rest.
Interesting question!
capitalize transforms every first letter of a word to uppercase, but it does not transform the other letters to lowercase. Not even the :first-letter pseudo-class will cut it (because it applies to the first letter of each element, not each word), and I can't see a way of combining lowercase and capitalize to get the desired outcome.
So as far as I can see, this is indeed impossible to do with CSS.
#Harmen shows good-looking PHP and jQuery workarounds in his answer.
I'd like to sugest a pure CSS solution that is more useful than the first letter solution presented but is also very similar.
.link {
text-transform: lowercase;
display: inline-block;
}
.link::first-line {
text-transform: capitalize;
}
<div class="link">HELLO WORLD!</div>
<p class="link">HELLO WORLD!</p>
HELLO WORLD! ( now working! )
Although this is limited to the first line it may be useful for more use cases than the first letter solution since it applies capitalization to the whole line and not only the first word. (all words in the first line)
In the OP's specific case this could have solved it.
Notes: As mentioned in the first letter solution comments, the order of the CSS rules is important! Also note that I changed the <a> tag for a <div> tag because for some reason the pseudo-element ::first-line doesn't work with <a> tags natively but either <div> or <p> are fine.
EDIT: the <a> element will work if display: inline-block; is added to the .link class. Thanks to Dave Land for spotting that!
New Note: if the text wraps it will loose the capitalization because it is now in fact on the second line (first line is still ok).
JavaScript:
var links = document.getElementsByClassName("link");
for (var i = 0; i < links.length; i++) {
links[i].innerHTML = links[i].innerHTML.toLowerCase();
}
CSS:
.link { text-transform: capitalize; }
What Khan "ended up doing" (which is cleaner and worked for me) is down in the comments of the post marked as the answer.
captialize only effects the first letter of the word. http://www.w3.org/TR/CSS21/text.html#propdef-text-transform
You can do it with css first-letter!
eg I wanted it for the Menu:
a {display:inline-block; text-transorm:uppercase;}
a::first-letter {font-size:50px;}
It only runs with block elements - therefore the inline-block!
May be useful for java and jstl.
Initialize variable with localized message.
After that it is possible to use it in jstl toLowerCase function.
Transform with CSS.
In JSP
1.
<fmt:message key="some.key" var="item"/>
2.
<div class="content">
${fn:toLowerCase(item)}
</div>
In CSS
3.
.content {
text-transform:capitalize;
}
If the data is coming from a database, as in my case, you can lower it before sending it to a select list/drop down list. Shame you can't do it in CSS.
After researching a lot I found jquery function/expression to change text in first letter in uppercase only, I modify that code accordingly to make it workable for input field. When you will write something in input field and then move to another filed or element, the text of that field will change with 1st-letter capitalization only. No matter user type text in complete lower or upper case capitalization:
Follow this code:
Step-1: Call jquery library in html head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Step-2: Write code to change text of input fields:
<script>
$(document).ready(function(){
$("#edit-submitted-first-name,#edit-submitted-last-name,#edit-submitted-company-name, #edit-submitted-city").focusout(function(){
var str=$(this).val();
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
$(this).val(str);
});});
</script>
Step-3: Create HTML input fields with same id's you use in jquery code like:
<input type="text" id="edit-submitted-first-name" name="field name">
The id of this input field is: edit-submitted-first-name (It using in jquery code in step-2)
**Result:
Make sure the text will change after you move your focus from that input field at another element. Because we using focus out event of jquery here.
Result should like this: User Type: "thank you" it will change with "Thank You".
**
Best of luck
The PHP solution, in backend:
$string = 'UPPERCASE';
$lowercase = strtolower($string);
echo ucwords($lowercase);
I know this is a late response but if you want to compare the performance of various solutions I have a jsPerf that I created.
Regex solutions are the fastest for sure.
Here is the jsPerf: https://jsperf.com/capitalize-jwaz
There are 2 regex solutions.
The first one uses/\b[a-z]/g. Word boundary will capital words such as non-disclosure to Non-Disclosure.
If you only want to capitalize letters that are preceded by a space then use the second regex
/(^[a-z]|\s[a-z])/g
if you are using jQuery; this is one a way to do it:
$('.link').each(function() {
$(this).css('text-transform','capitalize').text($(this).text().toLowerCase());
});
Here is an easier to read version doing the same thing:
//Iterate all the elements in jQuery object
$('.link').each(function() {
//get text from element and make it lower-case
var string = $(this).text().toLowerCase();
//set element text to the new string that is lower-case
$(this).text(string);
//set the css to capitalize
$(this).css('text-transform','capitalize');
});
Demo
all wrong it does exist --> font-variant: small-caps;
text-transform:capitalize; just the first letter cap

Resources