The goal is to filter some "test" or "flood" messages in a shout box chat.
ex: when an user writes something like
aaaaaaaaaaaaaaaaaaaaa or jdhshjdskhdshuishifhduif or dsqjlkdsqjiodsqjiosqjdsjq
I want to filter such stupid words: I guess I need to write some functions like:
if string length>20 or string conatins more that 4 vowels in a row or contains 4 consonants in a row
or contains some special chars...
Maybe this function has aleardy been written to avoid reinventing the wheel.
regards
Well using some Regular Expressions could do the trick.
EDIT
I have updated the code after Chris's suggestion.
So the credit goes to him.
String.prototype.testVowels = function () {
return !(/([aeiou]){4,}\w*/g.test(this));
}
String.prototype.testConsonants = function () {
return !(/([bcdfghjklmnpqrstwxyz]){4,}\w*/g.test(this));
}
String.prototype.testLength = function() {
return this.length < 20;
}
function testString(str) {
var stringArr = str.split(" ");
// this will test for each word in the str parameter
stringArr.forEach(function(s) {
if(s.testConsonants() && s.testLength() && s.testVowels()) {
console.log("The word " + s + " is ok !");
}
});
}
So I am using Node.JS and doing a small multiplayer project.
Of course I'm using JavaScript for a lot of things.
I would like to check if a div contains a certain word and if that certain word matches a variable.
How would I do this with JavaScript?
I want something like:
var teststring = "hi";
if "<div id="test">" contents matches "teststring"
{
}
I also have jQuery so that's an option too!
I'm new to JavaScript so please fire away!
This was my attempt but it didn't work:
var socket = io.connect('http://*');
socket.on('field', function (data) {
if ($("#userid").text().indexOf(data) > -1)
{
window.alert('lol');
console.log(data);
$("#field").html(data);
}
else
{
window.alert("Something has gone wrong with the node server...");
}
});
Just check the contents of the div with the text() function of jQuery, like this:
var teststring = "hi";
if ($("#test").text().indexOf(teststring) > -1)
{
alert("Match!");
}
to get the value of the div you can use
var divValue = $('#test').text();
var teststring = "hi";
and to match with the variable;
if(divValue === teststring ){
alert('Two variables are matching !!');
}
and to search a String contains a substring you can use;
if (divValue.indexOf(teststring ) >= 0)
{
alert('Two variables are matching !!');
}
please visit http://jsfiddle.net/dennypanther/ojmyobL8/
In JavaScript u can do it lyk this :
var teststring = "hi";
var div=document.getElementById('test').innerHTML;
if(div.indexOf(testString) > -1 ){
// your code goes here
}
let´s say I have a string in JavaScript:
var str = '<span class="color:red;">Hello</span> my name is <span class="color:red;">Julian</span>';
So I would like to print each 300ms one character so that it looks as if it is being entered. Sure I can make a for-loop for each character and print it inside an element, but the problem is the formatting. If I use the for-loop it will even print the span-tag separately, but that will causing problems.
How to print every character after a while with formatting?
This quite an evil trick but you can use a white div on top of your string and move it step by step every 300ms. In this way a letter appears every 300ms. The only problem is to determine how big each step needs to be since the width of each character will vary.
A way to determine the width is to load all the characters separate in a div and measure the width. Of course you first need to strip the html. In order to so you could use How to strip HTML tags with jQuery?
You could split all characters into an array and then loop like this:
var str = '<span class="red">Hello</span> my name is <span class="red">Julian</span>',
AllChars = [],
SetTxt = true,
newstr = '';
for (var i = 0; i < str.length; i++) {
newstr += str.substr(i,1);
if((str.substr(i,1) == '<') || (str.substr(i,1) == '&')){
SetTxt = false;
}else if(SetTxt){
AllChars.push(newstr);
}else if((str.substr(i,1) == '>') || (str.substr(i,1) == ';')){
if(str.length == (i+1)){
AllChars.push(newstr);
}
SetTxt = true;
}
}
for (var i in AllChars){
setTimeout(function(i){
$('#text').html(AllChars[i]);
},300 * i,i);
}
Check the jsfiddle for a working example: http://jsfiddle.net/2R9Dk/1/
You need to parse html tags and text separately. Something like:
var str = '<span class="colored">Hello</span> my name is <span class="colored bold">Julian</span>';
function printTextByLetter(text, selector, speed) {
var html = text.match(/(<[^<>]*>)/gi),
sel = selector || 'body',
arr = text.replace(/(<[^<>]*>)/gi, '{!!}').match(/(\{!!\}|.)/gi),
counter = 0, cursor = jQuery(sel), insideTag,
interval = setInterval(printChar, speed);
function printChar() {
if(arr[0]){
if(arr[0] === '{!!}') {
if(!insideTag) {
insideTag = true;
cursor.append(html[0], html[1]);
html.shift();
html.shift();
cursor = cursor.children().eq(counter);
} else {
insideTag = false;
cursor = cursor.parent();
counter++;
}
} else {
cursor.append(arr[0]);
}
arr.shift();
} else {
clearInterval(interval);
}
}
}
// DOM ready
jQuery(function($){
printTextByLetter(str, '#target', 300);
});
And don't forget to clear intervals - it does affect performance.
Example on JSFiddle: http://jsfiddle.net/36kLf/7/
the questions says it all :)
eg. we have >, we need > using only javascript
Update: It seems jquery is the easy way out. But, it would be nice to have a lightweight solution. More like a function which is capable to do this by itself.
You could do something like this:
String.prototype.decodeHTML = function() {
var map = {"gt":">" /* , … */};
return this.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);?/gi, function($0, $1) {
if ($1[0] === "#") {
return String.fromCharCode($1[1].toLowerCase() === "x" ? parseInt($1.substr(2), 16) : parseInt($1.substr(1), 10));
} else {
return map.hasOwnProperty($1) ? map[$1] : $0;
}
});
};
function decodeEntities(s){
var str, temp= document.createElement('p');
temp.innerHTML= s;
str= temp.textContent || temp.innerText;
temp=null;
return str;
}
alert(decodeEntities('<'))
/* returned value: (String)
<
*/
I know there are libraries out there, but here are a couple of solutions for browsers. These work well when placing html entity data strings into human editable areas where you want the characters to be shown, such as textarea's or input[type=text].
I add this answer as I have to support older versions of IE and I feel that it wraps up a few days worth of research and testing. I hope somebody finds this useful.
First this is for more modern browsers using jQuery, Please note that this should NOT be used if you have to support versions of IE before 10 (7, 8, or 9) as it will strip out the newlines leaving you with just one long line of text.
if (!String.prototype.HTMLDecode) {
String.prototype.HTMLDecode = function () {
var str = this.toString(),
$decoderEl = $('<textarea />');
str = $decoderEl.html(str)
.text()
.replace(/<br((\/)|( \/))?>/gi, "\r\n");
$decoderEl.remove();
return str;
};
}
This next one is based on kennebec's work above, with some differences which are mostly for the sake of older IE versions. This does not require jQuery, but does still require a browser.
if (!String.prototype.HTMLDecode) {
String.prototype.HTMLDecode = function () {
var str = this.toString(),
//Create an element for decoding
decoderEl = document.createElement('p');
//Bail if empty, otherwise IE7 will return undefined when
//OR-ing the 2 empty strings from innerText and textContent
if (str.length == 0) {
return str;
}
//convert newlines to <br's> to save them
str = str.replace(/((\r\n)|(\r)|(\n))/gi, " <br/>");
decoderEl.innerHTML = str;
/*
We use innerText first as IE strips newlines out with textContent.
There is said to be a performance hit for this, but sometimes
correctness of data (keeping newlines) must take precedence.
*/
str = decoderEl.innerText || decoderEl.textContent;
//clean up the decoding element
decoderEl = null;
//replace back in the newlines
return str.replace(/<br((\/)|( \/))?>/gi, "\r\n");
};
}
/*
Usage:
var str = ">";
return str.HTMLDecode();
returned value:
(String) >
*/
Here is a "class" for decoding whole HTML document.
HTMLDecoder = {
tempElement: document.createElement('span'),
decode: function(html) {
var _self = this;
html.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);/gi,
function(str) {
_self.tempElement.innerHTML= str;
str = _self.tempElement.textContent || _self.tempElement.innerText;
return str;
}
);
}
}
Note that I used Gumbo's regexp for catching entities but for fully valid HTML documents (or XHTML) you could simpy use /&[^;]+;/g.
There is nothing built in, but there are many libraries that have been written to do this.
Here is one.
And here one that is a jQuery plugin.
I'm looking for an example of how to capitalize the first letter of a string being entered into a text field. Normally, this is done on the entire field with a function, regex, OnBlur, OnChange, etc. I want to capitalize the first letter while the user is still typing.
For instance, if I'm typing the word "cat", the user should press 'c', and then by the time he presses 'a', the C should be capitalized in the field.
I think what I'm going for might be possible with keyup or keypress but I'm not sure where to start.
Anyone have an example for me?
Just use CSS.
.myclass
{
text-transform:capitalize;
}
This will simply transform you first letter of text:
yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);
I answered this somewhere else . However, here are two function you might want to call on
keyup event.
To capitalize first word
function ucfirst(str,force){
str=force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
And to capitalize all words
function ucwords(str,force){
str=force ? str.toLowerCase() : str;
return str.replace(/(\b)([a-zA-Z])/g,
function(firstLetter){
return firstLetter.toUpperCase();
});
}
As #Darrell Suggested
$('input[type="text"]').keyup(function(evt){
// force: true to lower case all letter except first
var cp_value= ucfirst($(this).val(),true) ;
// to capitalize all words
//var cp_value= ucwords($(this).val(),true) ;
$(this).val(cp_value );
});
Hope this is helpful
Cheers :)
$('input[type="text"]').keyup(function(evt){
var txt = $(this).val();
// Regex taken from php.js (http://phpjs.org/functions/ucwords:569)
$(this).val(txt.replace(/^(.)|\s(.)/g, function($1){ return $1.toUpperCase( ); }));
});
CSS solution with "text-transform: capitalize;" is no good if you want to use the contents of the input in backend. You will still receive data as-is. JavaScript solves this issue.
JQuery plugin combined from some of the techniques mentioned earlier, plus it capitalizes words after hyphens, i.e.: "Tro Lo-Lo":
Add to your script:
jQuery.fn.capitalize = function() {
$(this[0]).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
$(this).val(txt.replace(/^(.)|(\s|\-)(.)/g, function($word) {
return $word.toUpperCase();
}));
box.setSelectionRange(stringStart , stringEnd);
});
return this;
}
Then just attach capitalize() to any selector:
$('#myform input').capitalize();
I used the code of #Spajus and wrote a more extended jQuery plugin.
I wrote these four jQuery functions:
upperFirstAll() to capitalize ALL words in an inputfield
upperFirst() to capitalize only the FIRST word
upperCase() to convert the hole text to upper case
lowerCase() to convert the hole text to lower case
You can use and chain them like any other jQuery function:
$('#firstname').upperFirstAll()
My complete jQuery plugin:
(function ($) {
$.fn.extend({
// With every keystroke capitalize first letter of ALL words in the text
upperFirstAll: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)(.)/g,
function(c) {
return c.toUpperCase();
}));
box.setSelectionRange(start, end);
});
return this;
},
// With every keystroke capitalize first letter of the FIRST word in the text
upperFirst: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase().replace(/^(.)/g,
function(c) {
return c.toUpperCase();
}));
box.setSelectionRange(start, end);
});
return this;
},
// Converts with every keystroke the hole text to lowercase
lowerCase: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toLowerCase());
box.setSelectionRange(start, end);
});
return this;
},
// Converts with every keystroke the hole text to uppercase
upperCase: function() {
$(this).keyup(function(event) {
var box = event.target;
var txt = $(this).val();
var start = box.selectionStart;
var end = box.selectionEnd;
$(this).val(txt.toUpperCase());
box.setSelectionRange(start, end);
});
return this;
}
});
}(jQuery));
Groetjes :)
My personal favorite when using jQuery is short and sweet:
function capitalize(word) {
return $.camelCase("-" + word);
}
There's a jQuery plugin that does this too. I'll call it... jCap.js
$.fn.extend($, {
capitalize: function() {
return $.camelCase("-"+arguments[0]);
}
});
$("#test").keyup(
function () {
this.value = this.value.substr(0, 1).toUpperCase() + this.value.substr(1).toLowerCase();
}
);
Slight update to the code above to force the string to lower before Capitaliing the first letter.
(Both use Jquery syntax)
function CapitaliseFirstLetter(elemId) {
var txt = $("#" + elemId).val().toLowerCase();
$("#" + elemId).val(txt.replace(/^(.)|\s(.)/g, function($1) {
return $1.toUpperCase(); }));
}
In addition a function to Capitalise the WHOLE string:
function CapitaliseAllText(elemId) {
var txt = $("#" + elemId).val();
$("#" + elemId).val(txt.toUpperCase());
}
Syntax to use on a textbox's click event:
onClick="CapitaliseFirstLetter('myTextboxId'); return false"
this will help you in - convert first letter of each word to uppercase
<script>
/* convert First Letter UpperCase */
$('#txtField').on('keyup', function (e) {
var txt = $(this).val();
$(this).val(txt.replace(/^(.)|\s(.)/g, function ($1) {
return $1.toUpperCase( );
}));
});
</script>
Example : this is a title case sentence -> This Is A Title Case Sentence
My appologies. The syntax was off due to me being in a hurry and sloppy. Here you go...
$('#tester').live("keyup", function (evt)
{
var txt = $(this).val();
txt = txt.substring(0, 1).toUpperCase() + txt.substring(1);
$(this).val(txt);
});
Simple but works. You would def want to make this more general and plug and playable. This is just to offer another idea, with less code. My philosophy with coding, is making it as general as possible, and with as less code as possible.
Hope this helps. Happy coding! :)
It's very cool you can capitalize Only the first letter of an input field With this one.. If any one know how to capitalize Like CSS text-transform:capitalize, Please Reply ..
Here You go..
$('input-field').keyup(function(event) {
$(this).val(($(this).val().substr(0,1).toUpperCase())+($(this).val().substr(1)));
});
If using Bootstrap, add:
class="text-capitalize"
For example:
<input type="text" class="form-control text-capitalize" placeholder="Full Name" value="">
A turkish one. If someone is still interested.
$('input[type="text"]').keyup(function() {
$(this).val($(this).val().replace(/^([a-zA-Z\s\ö\ç\ş\ı\i\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü])|\s+([a-zA-Z\s\ö\ç\ş\ı\i\ğ\ü\Ö\Ç\Ş\İ\Ğ\Ü])/g, function ($1) {
if ($1 == "i")
return "İ";
else if ($1 == " i")
return " İ";
return $1.toUpperCase();
}));
});
With Javascript you can use:
yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);
If by chance you're generating your web page with PHP you can also use:
<?=ucfirst($your_text)?>
Jquery or Javascipt doesn't provide a built-in method to achieve this.
CSS test transform (text-transform:capitalize;) doesn't really capitalize the string's data but shows a capitalized rendering on the screen.
If you are looking for a more legit way of achieving this in the data level using plain vanillaJS, use this solution =>
var capitalizeString = function (word) {
word = word.toLowerCase();
if (word.indexOf(" ") != -1) { // passed param contains 1 + words
word = word.replace(/\s/g, "--");
var result = $.camelCase("-" + word);
return result.replace(/-/g, " ");
} else {
return $.camelCase("-" + word);
}
}
I use both CSS and jQuery solutions when achieving this. This will change both how it appears in the browser and the data value. A simple solution, that just works.
CSS
#field {
text-transform: capitalize;
}
jQuery
$('#field').keyup(function() {
var caps = jQuery('#field').val();
caps = caps.charAt(0).toUpperCase() + caps.slice(1);
jQuery('#field').val(caps);
});
A solution that accept exceptions(passed by parameters):
Copy the below code and use it like this: $('myselector').maskOwnName(['of', 'on', 'a', 'as', 'at', 'for', 'in', 'to']);
(function($) {
$.fn.maskOwnName = function(not_capitalize) {
not_capitalize = !(not_capitalize instanceof Array)? []: not_capitalize;
$(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] = words[i].substring(0,1).toUpperCase() + words[i].substring(1,words[i].length).toLowerCase();
}
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();
});
}
})(jQuery);
.first-character{
font-weight:bold;
color:#F00;
text-transform:capitalize;
}
.capital-text{
text-transform:uppercase;
}
My attempt.
Only acts if all text is lowercase or all uppercase, uses Locale case conversion. Attempts to respect intentional case difference or a ' or " in names.
Happens on Blur as to not cause annoyances on phones.
Although left in selection start/end so if changed to keyup maybe useful still.
Should work on phones but have not tried.
$.fn.capitalize = function() {
$(this).blur(function(event) {
var box = event.target;
var txt = $(this).val();
var lc = txt.toLocaleLowerCase();
var startingWithLowerCaseLetterRegex = new RegExp("\b([a-z])", "g");
if (!/([-'"])/.test(txt) && txt === lc || txt === txt.toLocaleUpperCase()) {
var stringStart = box.selectionStart;
var stringEnd = box.selectionEnd;
$(this).val(lc.replace(startingWithLowerCaseLetterRegex, function(c) { return c.toLocaleUpperCase() }).trim());
box.setSelectionRange(stringStart, stringEnd);
}
});
return this;
}
// Usage:
$('input[type=text].capitalize').capitalize();
Slight update to cumul's solution.
The function upperFirstAll doesn't work properly if there is more than one space between words. Replace the regular expression for this one to solve it:
$(this).val(txt.toLowerCase().replace(/^(.)|(\s|\-)+(.)/g,