how can i avoid counting double spaces as words? - javascript

$(document).ready(function() {
$("[class^='count[']").each(function() {
var elClass = $(this).attr('class');
var minWords = 0;
var maxWords = 0;
var countControl = elClass.substring((elClass.indexOf('['))+1, elClass.lastIndexOf(']')).split(',');
if(countControl.length > 1) {
minWords = countControl[0];
maxWords = countControl[1];
}
else { maxWords = countControl[0]; }
$(this).after('<div class="wordCount"><strong>0</strong> words so far</div>');
if(minWords > 0) {
$(this).siblings('.wordCount').addClass('error');
}
$(this).bind('keyup click blur focus change paste', function() {
var numWords = jQuery.trim($(this).val()).split(' ').length;
if($(this).val() === '') {
numWords = 0;
}
$(this).siblings('.wordCount').children('strong').text(numWords);
if(numWords < minWords || (numWords > maxWords && maxWords != 0)) {
$(this).siblings('.wordCount').addClass('error');
}
else {
$(this).siblings('.wordCount').removeClass('error');
}
});
});
});
this script basically counts the spaces between words but if extra spaces are added it counts them as new words too...
http://blog.themeforest.net/tutorials/creating-a-jquery-word-counter/

.split() also accepts regular expressions. Try this:
var numWords = jQuery.trim($(this).val()).split(/\s+/).length;

Remove all double spaces with a Regex and then do your script. If there are no double spaces to find, it cannot count them.
This is an example in C#, but the same accounts for javascript: How do I replace multiple spaces with a single space in C#?

Related

Replace last matched character in substring using jquery / regex

I know this question is similar to THIS so apologies if considered a duplicate.
The result I'm trying to achieve is to check divs with a class of gallery-info
$('.gallery-info').each(function() {
});
I set up a condition to return a substring if the character count of each div is greater than 140 characters. (Twitter)
$('.gallery-info').each(function() {
var descLength = 140;
var str = $(this).text();
var patt = new RegExp(/[,;.:!()&\s$]/g);
if (str.length > descLength) {
$(this).text(str.substr(0, descLength) + "...");
}
});
IF
The last character of the substring matches the patt var.
Return substring -1 and concat "..."
ELSE
Return substring and concat "..."
I've been having a brain fart on this and I believe I can achieve this in Vanilla JS with str.replace() and str.charAt() but I need to do this in jQuery.
I think updating your IF condition with below should work fine.
if (str.length > descLength) {
if(patt.test(str[descLength-1])) {
$(this).text(str.substr(0, descLength-1) + "...");
} else {
$(this).text(str.substr(0, descLength) + "...");
}
}
CODEPEN: https://codepen.io/azimjs/pen/mBqjNY
I think this works as you've described.
$('.gallery-info').each(function() {
var descLength = 140;
var str = $(this).text();
var patt = new RegExp(/[,;.:!()&\s$]/g);
if (str.length > descLength) {
var substring = str.substr(0, descLength);
var lastChar = substring[substring.length-1];
if (lastChar.match(patt)) {
$(this).text(str.substr(0, descLength -1) + "...");
} else {
$(this).text(str.substr(0, descLength) + "...");
}
}
});
Codepen
https://codepen.io/foozie3moons/pen/GMOBvw

Check whether a word is in a text box regardless of case

I am trying to figure out whether a text box has a given word, regardless of case. For example, how can I determine whether a given text box, #TextBox, has the word "hello" in it?
var specialwords = ['hello','Hello','HELLO']; //special words here
$('#TextBox').keydown(function() {
var text = $(this).val();
text = text.split(" ");
var newtext = "";
for(var i = 0; i < text.length; i++){
// code to check words
}
$("#check").html(newtext);
});
The easiest way to check whether a text box has a given word, irrespective of case, is to convert the text box to lowercase, then split by spaces and find the indexOf the word.
var word = "hello".toLowerCase(); // make sure this word is lowercase
$("#TextBox").keydown(function () {
var text = $(this).val().toLowerCase().split(" ");
if (text.indexOf(word) > -1) {
// do something
} else {
// word is not in the text box
}
})
If you want to check for an array of words, specialWords, wrap the if block in a for loop. This would be O(n²) complexity, but that should be fine, as long as your input isn't extremely long1.
1we're talking thousands upon thousands of words long for it to matter.
function checkAlphaCase(alpha) {
if (alpha == alpha.toLowerCase()) {
alert('LowerCase');
} else if (alpha == alpha.toUpperCase()) {
alert('UppperCase');
} else {
alert('MixedCase');
}
}
checkAlphaCase('ANIR');
TRY this
$(document).ready(function(){
var specialwords = ['hello','Hello','HELLO'];//special words here
$('#TextBox').keydown(function() {
//alert(this);
var text = $(this).val().trim();
console.log(text);
// text = text.trim().split(" ");
var newtext = "";
var up=0,low=0;
for(var i=0;i<text.length;i++){
if(text[i]==" ")
continue;
else{
if(text[i].trim()==text[i].trim().toLowerCase())
low++;
if(text[i].trim()==text[i].trim().toUpperCase())
up++;
}
}
if(up>0 && low>0)
newtext="mix case";
else if(up>0)
newtext="Upper case";
else if(low>0)
newtext="Lower case"
$("#check").html(newtext);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="TextBox">
<div id="check"></div>
You can make a case insensitive regex with all the words like this:
RegExp("\\b(?:" + specialwords.join("|") + ")\\b", "i")
then you can use it against each word. I am not sure what you are doing with the words once you identify them ... I will assume for the purpose of my code snippet that you are ignoring them from the text.
var specialwords = ['hello','world','pizza']; //special words here
var swr = RegExp("\\b(?:" + specialwords.join("|") + ")\\b", "i")
$('#TextBox').keydown(function() {
var text = $(this).val();
text = text.split(" ");
var newtext = [];
for(var i=0; i<text.length; i++){
if (!text.match(swr)) {
newtext.push(text)
}
}
$("#check").html(newtext.join(" "));
});
Using the \b as a word delimiter in regexp you can also check the whole text without breaking up the words if you want.
var specialwords = ['hello','world','pizza']; //special words here
var swr = RegExp("\\b(?:" + specialwords.join("|") + ")\\b", "i")
$('#TextBox').keydown(function() {
var text = $(this).val();
var newtext = text.replace(swr, "");
$("#check").html(newtext);
});

jQuery get numbers inside paragraph, but not those in classes

I have the following HTML structure:
<div class="content">
<p>somecontent</p>
<p>another content <span id="name-1">content</span> 1234214</p>
</div>
I want to wrap only numbers in additional span (1234214). So far I've made this:
jQuery(window).load(function() {
jQuery('.content p').html(function(index, value) {
return value.replace(/(\d+)/g, '<span class="mathjaxfont">$1</span>');
});
});
However this replaces the 1 in span id. How can I exclude checking element attributes?
You might want not only to exclude attributes (think about the h1-element for example) but constrain your replacing on the text nodes. See this questions for some ideas on how to get only and work with text nodes: How do I select text nodes with jQuery?
This answer in above question How do I select text nodes with jQuery? gives you a collection of text-nodes on which you can do your string-replacing.
You should use .contents() and .replaceWith() for this:
jQuery('.content p').contents().each(function() {
var method = this.nodeType == 1 ? 'html' : 'replaceWith';
$(this)[method](this.textContent.replace(
/(\d+)/g,
'<span class="mathjaxfont">$1</span>'
));
});
Here's a JSFiddle.
Long and hard solution, but should work in nested elements.
The idea is to handle element's .html() string character by character, wrapping numbers when they are found, but omitting numbers inside tags' definition.
Fiddle.
$(document).ready(function()
{
$('.content p').each(function()
{
$(this).html(handleHtml($(this).html()));
});
});
function handleHtml(html)
{
var resultHtml = "";
var numberStr = "";
var re = /[0-9]/;
var isTag = false, quote = "";
for (var i = 0; i < html.length; i++)
{
var char = html.substr(i, 1);
if (!isTag && re.test(char))
{
numberStr += char;
}
else
{
if (numberStr)
{
resultHtml += wrapNumber(numberStr);
numberStr = "";
}
resultHtml += char;
if (isTag && !quote && (char == '"' || char == "'"))
{
quote = char;
}
else if (quote && quote == char)
{
quote = "";
}
if (char == '<')
{
isTag = true;
}
else if (!quote && char == '>')
{
isTag = false;
}
}
}
if (numberStr)
{
resultHtml += wrapNumber(numberStr);
}
return resultHtml;
}
function wrapNumber(number)
{
return '<span class="mathjaxfont">' + number+ "</span>";
}

Remove extra white spaces from Array

The elements in my list should be
A1,A2,A3,A4
If user input A1,A2,A3,A4,,,,,,
or
A1,A2,,,A3,A4,,A5,,
or
A,B, ,, ,, V,,,, , , , , ,ddfd ,,,,,,,,
It should consider as
A1,A2,A3,A4
The logic written by me was
if(valueText !== null) { alert("Value Text..." + valueText);
valueList = valueText.split(",");
for (var i = 0; i < valueList.length; i++)
{
if (valueList[i] == "")
{
valueList.splice(i, 1);
alert("ValueList inside for if.."+valueList);
}
}
alert("ValueList.." + valueList);
}
But its not working properly
You can do something like this with match & join functions:-
var str = "A1,A2,,,A3,A4,,A5,,";
strnew = str.match(/[^ ,]+/g).join(',');
//Output--> A1,A2,A3,A4,A5
Hope this will help you...
You can do this with regex, for example:
var txt = 'A1,A2,,,A3,A4,,A5,,'
var res = txt.replace(/(,)\1*/g, ',').replace(/,$/, '');
//^ A1,A2,A3,A4,A5

How to allow only one space in JavaScript real time filtering

I' am use this custom function below to strip out unwanted characters from the textfield, this is done real time. The problem is that it allows spaces and users can enter as many spaces as they want, but I want allow only one space.
Is it possible?
function mask8(x){
var string = document.getElementById(x)
var regex = /[^A-Za-z ]/gi;
$("#"+x).removeClass("error");
if(string.value.search(regex) > -1) {
string.value = string.value.replace(regex, "");
$("#"+x).addClass("error");
}
}
If you just want to automatically collapse multiple spaces down to a single space without making it an error condition, you can do this:
function mask8(x){
var obj = document.getElementById(x);
var val = obj.value;
var illegalChars = /[^A-Za-z ]/gi;
$("#"+x).removeClass("error");
// automatically collapse multiple spaces down to a single space,
// don't make it an error condition
val = val.replace(/\s+/g, " ");
if(val.search(illegalChars) > -1) {
val = val.replace(illegalChars, "");
$("#"+x).addClass("error");
}
obj.value = val;
}
If you want to make multiple spaces an error condition, then you could do this:
function mask8(x){
var obj = document.getElementById(x);
var val = obj.value;
var illegalChars = /[^A-Za-z ]/gi;
var illegalCharsOrMultipleSpaces = /[^A-Za-z ]|\s\s/gi;
$("#"+x).removeClass("error");
if(val.search(illegalCharsOrMultipleSpaces) > -1) {
obj.value = val.replace(illegalChars, "").replace(/\s+/g, " ");
$("#"+x).addClass("error");
}
}

Categories