First lowercase the text then capitalize it. Is it possible with CSS? - 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.

Related

Is there a global CSS / SCSS / regex way to style only NUMBERS with a different font? [duplicate]

I am Using a Regional language unicode font-face in my site but the numbers are not looking good.
So I want to apply new font-style or css to numbers only..
please help
This can be done using CSS's unicode-range property which exists within #font-face.
The numbers 0 to 9 exist in Unicode within the range U+0030 to U+0039. So what you'll need to do is include a font alongside your existing font which specifically targets this range:
#font-face {
font-family: 'My Pre-Existing Font';
...
}
#font-face {
font-family: 'My New Font Which Handles Numbers Correctly';
...
unicode-range: U+30-39;
}
The result of this will be that every instance of Unicode characters U+0030 (0) through to U+0039 (9) will be displayed in the font which specifically targets that range, and every other character will be in your current font.
You can wrap all numbers in p tags with a <span class="number">:
CSS
.number {
font-family: Verdana;
}
jQuery
$('p').html(function(i, v){
return v.replace(/(\d)/g, '<span class="number">$1</span>');
});
But personally, I would go with James suggestion ;)
http://jsfiddle.net/ZzBN9/
There is no way to apply CSS to all numbers specifically. In each number tag you could add the attribute class='number' and then in the CSS you could add
.number {
font-family: arial;
}
Better with this
$('p').html(function(i, v){
return v.replace(/(\d+)/g, '<span class="number">$1</span>');
});
With + you avoid one span per complete number (span for 321), not one per each number found (span for 3 for 2 and for 1)
You can use the regex replace and detect the numbers then add the class
following code:
$('p').html(function(i,c) {
return c.replace(/\d+/g, function(v){
return "<span class='numbers'>" + v + "</span>";
});
});
.numbers
{
color:red;
font-size:30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
View 11 new out of 11 message(s) in your inbox
</p>

How to break a sentence into different parts in 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;
}

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

Capitalize after a point in css

Having enough people writing in upper case, I inserted the syntax text-transform: lowercase; or the text to be written in lower case and syntax ::first-letter for a capital is created after the beginning of each sentence after the point.
text-transform: lowercase; works fine but for ::first-letter he created me a capital letter at the beginning of the sentence but not after!
Is it possible to create CSS capitalized after a point?
Keep all data into a variable and split it with the point you want. Then display all array inside paragraph. This might be working.
var str = "What ever you want to do. Please do it here.";
var res = str.split(".");
then use for loop and getElementbyId to replace the content
Try this:
str = 'ABC. DEF. XYZ';
str2 = str.toLowerCase();
str3 = str2.replace(/\. /g, '.</span> <span class = caps>')
$('#output').html('<span class = caps>' + str3)
.caps {
display: inline-block;
}
.caps::first-letter {
text-transform: uppercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
Convert the entire string to lower case; then replace the . with span elements; apply CSS rules to the span elements so that they are block level, inline and first letter capitalised); and just to tidy up, add an opening <span> before the replacement string to match the closing tag at the end of the first sentence.
<html>
<head>
<style>
p::first-letter {
font-weight: bold;
color: red;
}
</style>
<script>
function myFunction() {
var str = document.getElementById('data').innerHTML;
var res = str.split(".");
var data = "";
for(i=0; i<(res.length-1); i++){
var data = data + "<p>"+res[i]+".</p>";
}
document.getElementById("data").innerHTML = data;
}
</script>
</head>
<body onload="myFunction()">
<div id="data">What ever you want to do. Please do it here.</div>
</body>
</html>
This will automatically change the data onload.
Have more questions leave me a message in grandamour

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