1) I'm trying to apply the first letter in uppercase and the other as lowercase. If the user write in the input, it should automatically transform. Examples:
"isaac guilherme araújo" to "Isaac Guilherme Araújo"
"iSAAC guILHErme aRAÚJO" to "Isaac Guilherme Araújo"
2) In Brazil there are names with connectives.
Examples: "das" "da" "dos" "do" "de" "e".
Carlos Eduardo Julio dos Santos
Carlos Eduardo dos Santos e Silva
Carlos Eduardo da Silva
3) I am having this problem to work with the name fields. With the following code, i could apply the first letter in uppercase, but the others as lowercase i couldn't. Then, according to problem number 2, if I write:
value entered: "douglas de oliveira júnior"
should be: "Douglas de Oliveira Júnior"
shouldn't: "douglas de Oliveira Júnior". //value shown with current code
function contains(str, search){
if(str.indexOf(search) >= 0){
return true;
} else {
return false;
}
}
$.fn.capitalize = function(str) {
$.each(this, function() {
var split = this.value.split(' ');
for (var i = 0, len = split.length; i < len; i++) {
var verify = (split[len - 1] == "D" || split[len - 1] == "d") && (str == "e" || str == "E") || (str == "o" || str == "O");
if (verify == false) {
if ( contains(split[i], 'de') == false && contains(split[i], 'do') == false) {
split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
}
}
}
this.value = split.join(' ');
});
return this;
};
$(".capitalize").keypress(function(e) {
var str = String.fromCharCode(e.which);
$(this).capitalize(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Nome: </label>
<input type="text" id="nome" name="nome" class="form-control input-sm capitalize">
I'm a new member here on Stackoverflow and I apologize for the mistakes, I am learning javascript. Thank you!
This solution also fixes connectives in uppercase, such as carlos DE silva.
Try it with the snippet below :)
var connectives = {
das: true,
da: true,
dos: true,
do: true,
de: true,
e: true
};
function capitalize(str) {
return str
.split(" ")
.map(function(word) {
return !connectives[word.toLowerCase()]
? word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
: word.toLowerCase();
})
.join(" ");
};
$(".capitalize").keyup(function() {
var cursorStart = this.selectionStart;
var cursorEnd = this.selectionEnd;
var capitalizedString = capitalize($(this).val());
$(this).val(capitalizedString);
this.setSelectionRange(cursorStart, cursorEnd);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Nome: </label>
<input type="text" id="nome" name="nome" class="form-control input-sm capitalize">
You could use a format function that capitalizes all words except those provided in a whitelist. Then format the input value whenever the user presses a key (doesn't work well if the user moves the input cursor around though):
function format(string, noCapList=[]) {
const words = string.toLowerCase().split(' ');
return words.map((word) => {
if(!word.length || noCapList.includes(word)) {
return word;
} else {
return word[0].toUpperCase() + word.slice(1);
}
}).join(' ');
}
const input = document.querySelector('input');
input.addEventListener('keyup', () => {
input.value = format(input.value, ["das", "da", "dos", "do", "de", "e"]);
});
<input/>
It looks like the issue with your code is in how you're formatting the input. I'm not 100% sure I understood the question, but this format function provides the output you were looking for.
for simplicity I used npm lodash
https://lodash.com/docs/4.17.11#capitalize
const _ = require('lodash');
const connectives = {
das: true,
da: true,
dos: true,
do: true,
de: true,
e: true
};
const nameToCapitalize = str.split(' ').map(word => connectives[word] ?
word.toLowercase : _.capitalize(word)).join(' ');
SimpleJ's answer is right, but to clarify your original approach: the "problem" is in the contains function - it actually does what it should according to it's name and returns true if the str contains search, so contains('douglas', 'do') === true; you already have the string split into separate words so just use split[i] !== "de" && split[i] !== "do" instead of the contains calls.
I have posted algorithm in FCC about title casing a sentence . Might it would help you!
function titleCase(str) {
//First Converted to lowercase in case of test cases are tricky ones
var spl=str.toLowerCase();
//Then Splitted in one word format as leaving one space as ' '
spl = spl.split(' ');
for(var i=0;i<spl.length;i++){
//Again Splitting done to split one letter from that respective word
var spl2= spl[i].split('');
// In specific word's letter looping has to be done in order to
// convert 0th index character to uppercase
for(var j=0;j<spl2.length;j++){
spl2[0]= spl2[0].toUpperCase();
}
// Then Joined Those letters to form into word again
spl[i] = spl2.join('');
}
// Then joined those words to form string
str = spl.join(' ');
return str;
}
titleCase("sHoRt AnD sToUt");
I found something that apparently was satisfactory. It even works when the user places the cursor in the middle of the input. I found it here:
Link - Stackoverflow
Can anyone here evaluate and tell me if have some problem with this code from the user Doglas?
function ucfirst (str) {
// discuss at: http://locutus.io/php/ucfirst/
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
var not_capitalize = ['de', 'da', 'do', 'das', 'dos', 'e'];
$.fn.maskOwnName = function(pos) {
$(this).keypress(function(e){
if(e.altKey || e.ctrlKey)
return;
var new_char = String.fromCharCode(e.which).toLowerCase();
if(/[a-zà-ú\.\, ]/.test(new_char) || e.keyCode == 8){
var start = this.selectionStart, end = this.selectionEnd;
if(e.keyCode == 8){
if(start == end)
start--;
new_char = '';
}
var new_value = [this.value.slice(0, start), new_char, this.value.slice(end)].join('');
var maxlength = this.getAttribute('maxlength');
var words = new_value.split(' ');
start += new_char.length;
end = start;
if(maxlength === null || new_value.length <= maxlength)
e.preventDefault();
else
return;
for (var i = 0; i < words.length; i++){
words[i] = words[i].toLowerCase();
if(not_capitalize.indexOf(words[i]) == -1)
words[i] = ucfirst(words[i]);
}
this.value = words.join(' ');
this.setSelectionRange(start, end);
}
});
$.fn.maskLowerName = function(pos) {
$(this).css('text-transform', 'lowercase').bind('blur change', function(){
this.value = this.value.toLowerCase();
});
};
$.fn.maskUpperName = function(pos) {
$(this).css('text-transform', 'uppercase').bind('blur change', function(){
this.value = this.value.toUpperCase();
});
};
};
$('.capitalize').maskOwnName();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Nome: </label>
<input type="text" id="nome" name="nome" class="form-control input-sm capitalize">
Related
I have a problem to auto separate when input field detect between words and letters in html. For example expected result, when I type "ABB9102", the input field auto change to "ABB 9102".
Below is my coding, this coding just can restrict in-front 3 characters, cannot detect between words and letters, if I type "ABCD9102", it cannot auto change to "ABCD 9102":
function space(str, after) {
if (!str) {
return false;
}
after = after || 3;
var v = str.replace(/[^\dA-Z]/g, ''),
reg = new RegExp(".{" + after + "}", "g");
return v.replace(reg, function(a) {
return a + ' ';
});
}
var el = document.getElementById('pin');
el.addEventListener('keyup', function() {
this.value = space(this.value, 3);
});
<input autocapitalize="off" autocorrect="off" maxlength=20 type="text" placeholder="type the pin" id="pin" name="pin" />
Hope someone can guide me on how to solve this problem. Thanks.
Not sure if this is what you want?
<input autocapitalize="off" autocorrect="off" maxlength=20 type="text" placeholder="type the pin" id="pin" name="pin" />
<script>
var el = document.getElementById('pin');
function make_space () {
var content = el.value;
var patt = content.match(/[^\d|^\s]\d/g);
var x;
if (patt != null)
for (x of patt) {
el.value = content.replace(x, x[0] + " " + x[1])
content = el.value;
}
var content = el.value;
var patt = content.match(/\d[^\d|^\s]/g);
var x;
if (patt != null)
for (x of patt) {
el.value = content.replace(x, x[0] + " " + x[1])
content = el.value;
}
}
el.addEventListener('keyup', make_space);
el.addEventListener('change', make_space);
</script>
function space(str) {
if (str) {
const getIntialThree = str.slice(0,3)
const restThreeLetter = str.slice(3)
const result = `${getIntialThree} ${restThreeLetter}`;
console.log(result)
}{
return false
}
}
// testing
const number = 'ABB9102'
space(number)
//output
> "ABB 9102"
Console.log is showing the correct result, but how can I add the same formatting to the input type while typing.
Input type is reset after every comma to zero.
1000 to 1,000
Please Help.
This code is working here
function numberWithCommas(number) {
if (isNaN(number)) {
return '';
}
var asString = '' + Math.abs(number),
numberOfUpToThreeCharSubstrings = Math.ceil(asString.length / 3),
startingLength = asString.length % 3,
substrings = [],
isNegative = (number < 0),
formattedNumber,
i;
if (startingLength > 0) {
substrings.push(asString.substring(0, startingLength));
}
for (i=startingLength; i < asString.length; i += 3) {
substrings.push(asString.substr(i, 3));
}
formattedNumber = substrings.join(',');
if (isNegative) {
formattedNumber = '-' + formattedNumber;
}
document.getElementById('test').value = formattedNumber;
}
<input type="number" id="test" class="test" onkeypress="numberWithCommas(this.value)">
Some notes:
Because you want commas, the type is not a number, it's a string
Because you want to work on the input after you type, it's onkeyup not onkeypressed
I have a solution that does a regex replace for 3 characters with 3 characters PLUS a comma:
var x = "1234567";
x.replace(/.../g, function(e) { return e + ","; } );
// Gives: 123,456,7
i.e. almost the right answer, but the commas aren't in the right spot. So let's fix it up with a String.prototype.reverse() function:
String.prototype.reverse = function() {
return this.split("").reverse().join("");
}
function reformatText() {
var x = document.getElementById('test').value;
x = x.replace(/,/g, ""); // Strip out all commas
x = x.reverse();
x = x.replace(/.../g, function(e) { return e + ","; } ); // Insert new commas
x = x.reverse();
x = x.replace(/^,/, ""); // Remove leading comma
document.getElementById('test').value = x;
}
<input id="test" class="test" onkeyup="reformatText()">
function numberWithCommas(x) {
var real_num = x.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
console.log(real_num);
document.getElementById('test').value = real_num;
}
<input type="number" id="test" onkeypress="numberWithCommas(this.value)">
Check out my fiddle here http://jsfiddle.net/6cqn3uLf/
You'd need another regex to limit to numbers but this will format based on the user's locale - which may be advantageous here.
<input id="mytext" type="text">
$(function () {
$('#btnformat').on('input propertychange paste', function () {
var x = $('#btnformat').val();
$('#btnformat').val(Number(x.replace(/,/g,'')).toLocaleString());
});
});
if jquery is not overhead for your application then you can use
https://code.google.com/p/jquery-numberformatter/
I need to define the text area to delete from 4th occurrence of (_) and preserve the extension.
before 12_345_678_900_xxxxxxxxxxxxxxx.jpg after 12_345_678_900.jpg,
before 34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg
after 34_567_890_123.jpg
Is it possible?
One solution is to find the nth occurence and then use substring.
var one='12_345_678_900_xxxxxxxxxxxxxxx.jpg'; // 12_345_678_900.jpg
function nth_occurrence (string, char, nth) {
var first_index = string.indexOf(char);
var length_up_to_first_index = first_index + 1;
if (nth == 1) {
return first_index;
} else {
var string_after_first_occurrence = string.slice(length_up_to_first_index);
var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);
if (next_occurrence === -1) {
return -1;
} else {
return length_up_to_first_index + next_occurrence;
}
}
}
console.log(one.substring(0,nth_occurrence(one,'_',4))+one.substring(one.indexOf('.')));
Sure, split by "_" and then join back the data you want:
var str = "12_345_678_900_xxxxxxxxxxxxxxx.jpg";
str = str.split("_").slice(0,4).join("_") + "."+ str.split(".").slice(-1)
console.log(str)
Regular Expressions are great for this sort of scenario:
const data1 = '12_345_678_900_xxxxxxxxxxxxxxx.jpg'
const data2 = '34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg'
const re = /^([^_]+_[^_]+_[^_]+_[^_]+).*(.jpg)$/;
var test1 = data1.replace(re, '$1$2');
var test2 = data2.replace(re, '$1$2');
Try it out: https://jsfiddle.net/648xt3qq/
There are probably a few different regular expression approaches that would get the job done
Maybe this works for you:
function clean() {
var el = document.getElementById('area');
el.value = el.value.replace(/^(.*?_.*?_.*?_.*?)(_.*?)(\..*?.*)$/gmi, '$1$3');
}
<form action="">
<textarea cols="50" rows="4" id="area">12_345_678_900_xxxxxxxxxxxxxxx.jpg
34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg</textarea><br />
<input type="submit" onclick="clean(); return false;" />
</form>
This question already has answers here:
Why does this code not only count vowels? [duplicate]
(3 answers)
Closed 7 years ago.
I need to debug this segment of code for a class and I have fixed a number of things but I'm not sure why it doesnt work. It is supposed to count the number of vowels in the phrase and return them in the div element i believe. However it always returns "undefined vowels"
Here is the html
<!doctype html>
<html>
<!-- vowels.html -->
<head>
<meta charset="utf-8">
<title>Vowels</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="vowels.js"></script>
</head>
<body>
<header>
<h1>I'd like to buy a vowel</h1>
</header>
<main>
<label>
Type a phrase here:
<input type='text' id='textBox'> </input>
</label>
<button id='countBtn' type='button'> <!--changed countButton to countBtn-->
Count Vowels (a,e,i,o,u)
</button>
<div id='outputDiv'>
</div>
</main>
<footer>
<hr>
<p>© UO CIS 111 2015 April™ LLC</p>
</footer>
</body>
</html>
and here is my JS
function countVowels() {
var textBox, phrase, i, pLength, letter, vowelCount; //removed alert count vowels
textBox = document.getElementById('textBox'); //corrected spelling of Element
phrase = textBox.value;
phrase = phrase.toLowerCase; //switched to lower case
for(i = 0; i < phrase.length; i+= 1) {
letter = phrase[i];
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') { //fixed the spelling of letter. added another = in letter = 'e'
vowelCount = vowelCount + 1;
}
}
alert(vowelCount + ' vowels');
var outArea = document.getElementById('outputDiv'); //corrected to outputDiv instead of outputId and put document. in front of the getElement
outArea.innerHTML = vowelCount + ' vowels in ' + phrase;
}
function init(){
alert('init vowels');
var countTag = document.getElementById('countBtn'); //switched to semi- colon and condensed to single line
countTag.onclick = countVowels;
}
window.onload = init;
Here is a JSFiddle
You can also use RegExp for slimmer code: http://jsfiddle.net/4o67u3js/
HTML:
<p id = "text">
Lorem ipsum dolor sit amet.
</p>
<p id = "result"># of vowels: <span></span></p>
JS:
$(function() {
var vowelsCount = $("#text").text().match(/[aeiou]/gi).length;
$("#result > span").html(vowelsCount);
});
Here's a more algorithmic solution. And, yes it defines a function on the prototype and those who are opposed to that practice can rewrite the function imperatively.
Plain JS:
var str = "Lorem ipsum dolor sit amet.";
String.prototype.vowelsCount = function() {
var str = this.toLowerCase(),
len = str.length,
index = 0,
vowels = ["a", "e", "i", "o", "u"],
count = 0;
for( ; index < len; vowels.indexOf(str[index++]) !== -1 ? count++ : count);
return count;
};
console.log(str.vowelsCount());
The first thing you need to do is make sure you're initializing your init() function on window load. Change window.onload = init; to window.onload = init().
Next, change your double-equals to a triple-equals. It's generally good practice to do so:
if (letter === 'a' || letter === 'e' || letter === 'i' || letter === 'o' || letter === 'u')
Then, to get your counter working, you need to call toLowerCase() in phrase = phrase.toLowerCase. It should look like this: phrase = phrase.toLowerCase()
Here is your fixed JS code:
function countVowels() {
var textBox, phrase, i, pLength, letter, vowelCount; //removed alert count vowels
textBox = document.getElementById('textBox'); //corrected spelling of Element
phrase = textBox.value;
phrase = phrase.toLowerCase(); //switched to lower case
vowelCount = 0;
for(i = 0; i < phrase.length; i+= 1) {
letter = phrase[i];
if (letter === 'a' || letter === 'e' || letter === 'i' || letter === 'o' || letter === 'u') { //fixed the spelling of letter. added another = in letter = 'e'
vowelCount++;
}
}
alert(vowelCount + ' vowels');
var outArea = document.getElementById('outputDiv'); //corrected to outputDiv instead of outputId and put document. in front of the getElement
outArea.innerHTML = vowelCount + ' vowels in ' + phrase;
}
function init(){
alert('init vowels');
var countTag = document.getElementById('countBtn'); //switched to semi- colon and condensed to single line
countTag.onclick = countVowels;
}
window.onload = init();
Would like to know how to check true and false and in return give error message if checked and the number is incorrect..
<input name="student1" type="text" size="1" id="studentgrade1"/>
<input name="student2" type="text" size="1" id="studentgrade2"/>
<input name="student3" type="text" size="1" id="studentgrade3"/>
so here we have 3 inputbox , now i would like to check the result by entering number into those inputbox.
studentgrade1 = 78
studentgrade2 = 49
studentgrade3 = 90
<< Using JavaScript >>
So If User entered wrong number e.g "4" into inputbox of (studentgrade1) display error..
same for otherinputbox and if entered correct number display message and says.. correct.
http://jsfiddle.net/JxfcH/5/
OK your question is kinda unclear but i am assuming u want to show error
if the input to the text-box is not equal to some prerequisite value.
here is the modified checkGrade function
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
VAR errText = "";
if (stud1.exists() && (parseInt(stud1.value) == 78){return true;}
else{errText += "stud1 error";}
//do similiar processing for stud2 and stud 3.
alert(errText);
}
See demo →
I think this is what you're looking for, though I would recommend delimiting your "answer sheet" variable with commas and then using split(',') to make the array:
// answers
var result ="756789";
// turn result into array
var aResult = [];
for (var i = 0, il = result.length; i < il; i+=2) {
aResult.push(result[i]+result[i+1]);
}
function checkgrade() {
var tInput,
msg = '';
for (var i = 0, il = aResult.length; i < il; i++) {
tInput = document.getElementById('studentgrade'+(i+1));
msg += 'Grade ' + (i+1) + ' ' +
(tInput && tInput.value == aResult[i] ? '' : 'in') +
'correct!<br>';
}
document.getElementById('messageDiv').innerHTML = msg;
}
See demo →
Try this http://jsfiddle.net/JxfcH/11/
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
var stud2 = document.getElementById("studentgrade2");
var stud3 = document.getElementById("studentgrade3");
if (((parseInt(stud1.value) == 78)) && ((parseInt(stud2.value) == 49)) && ((parseInt(stud3.value) == 90)))
{
alert("correct");
}
else
{
alert("error correct those values");
}
}