Line count shows 1 eventhough input field has no value - javascript

I am using below code to calculate words, characters and lines.
function wordCount( val ){
var wom = val.match(/\S+/g);
return {
charactersNoSpaces : val.replace(/\s+/g, '').length,
characters : val.length,
words : wom ? wom.length : 0,
lines : val.split(/\r*\n/).length
};
}
var textarea = document.getElementById("text");
var result = document.getElementById("result");
textarea.addEventListener("input", function(){
var v = wordCount( this.value );
result.innerHTML = (
"<br>Characters (no spaces): "+ v.charactersNoSpaces +
"<br>Characters (and spaces): "+ v.characters +
"<br>Words: "+ v.words +
"<br>Lines: "+ v.lines
);
}, false);
<textarea id="text"></textarea>
<div id="result"></div>
initially everything is set to zero. When we type it counts well. But when we clear the textbox, Lines shows value as 1 eventhough there is no texts in the textbox. How to make the line count zero?

I realized that splitting val make the length of it 1 even if it's empty:
// val is empty and it length is null
// But after splitting it would be one
val.split(/\r*\n/).length // 1
function wordCount( val ){
var wom = val.match(/\S+/g);
return {
charactersNoSpaces : val.replace(/\s+/g, '').length,
characters : val.length,
words : wom ? wom.length : 0,
lines : val.length ? val.split(/\r*\n/).length : val.length
};
}
var textarea = document.getElementById("text");
var result = document.getElementById("result");
textarea.addEventListener("input", function(){
var v = wordCount( this.value );
result.innerHTML = (
"<br>Characters (no spaces): "+ v.charactersNoSpaces +
"<br>Characters (and spaces): "+ v.characters +
"<br>Words: "+ v.words +
"<br>Lines: "+ v.lines
);
}, false);
<textarea id="text"></textarea>
<div id="result"></div>

If you split an empty string, the result is [""] -- an array with one element that's an empty string.
You can check for this case first with a conditional expression.
Also, there's no need to use \r* in the split delimiter, as it doesn't influence the count.
function wordCount( val ){
var wom = val.match(/\S+/g);
return {
charactersNoSpaces : val.replace(/\s+/g, '').length,
characters : val.length,
words : wom ? wom.length : 0,
lines : val.length == 0 ? 0 : val.split('\n').length
};
}
var textarea = document.getElementById("text");
var result = document.getElementById("result");
textarea.addEventListener("input", function(){
var v = wordCount( this.value );
result.innerHTML = (
"<br>Characters (no spaces): "+ v.charactersNoSpaces +
"<br>Characters (and spaces): "+ v.characters +
"<br>Words: "+ v.words +
"<br>Lines: "+ v.lines
);
}, false);
<textarea id="text"></textarea>
<div id="result"></div>

When a string is split, if none of the delimiters match, you'll be left with the original string.
const foo = 'foo';
console.log(foo.split(/bar/).length);
The same is true of the empty string - when split on, it'll still give you [''], which has a length..
You might match lines which have at least one character on them instead of splitting, thereby excluding empty lines.
lines: (val.match(/^./gm) || []).length

Related

jQuery phone number masking with Regex not working

I've been trying to mask the phone number into a region specific format.
$("input:text[name=phone_number]").keyup(function() {
var number = $(this).val().replace(/[^\d]/g, '');
number = number.replace(/(\d{3})(\d{3})(\d{3})/, "($1) $2-$3");
$(this).val(number);
});
The problem I am having with the script above is that regex is waiting for 3 numbers before it replaces the value in the input field.
And additionally I have to press enter for the effects to take place.
Is there a way I can make (\d{3}) this more dynamic. For example even if I've entered only 1 digit it should still display (0 ).
And then I continue entering (05 )... and so on...to a format that looks like this (051) 000-000?
I don't want to use additional plugins. I know there are many out there.
I made a simple mask, check:
$("input[name=phone_number]").keydown(function(e) {
var actualValue = e.key;
var baseMask = '(###) ###-###';
var valueInput = this.value.match(/\d/g);
if (actualValue !== 'Backspace' && /[^\d]/.test(actualValue)) {
return false;
}
if (actualValue === 'Backspace') {
if (!valueInput) {
return false;
}
valueInput.pop();
actualValue = '#';
}
var numsValues = valueInput ? valueInput.concat(actualValue) : [actualValue];
$.each(numsValues, function() {
baseMask = baseMask.replace(/\#/, this);
});
$(this).val(baseMask);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="phone_number">
$("#input").keyup(function() {
var number = $(this).val().replace(/[^\d]/g, "");
number = number.replace(/(\d{3})(\d{0,3})(\d{0,3})/, function(match, p1, p2, p3) {
if (p2.length < 1)
return "(" + p1 + ") ";
else if (p3.length < 1)
return "(" + p1 + ") " + p2;
return "(" + p1 + ") " + p2 + "-" + p3;
});
$(this).val(number);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id=input placeholder="type your number">

replace symbol-number to gif

I need your help.
Here I have text: hello #005 goodbye.
How to make js replace text starting with # by img like <img src=/img/005.gif> if number (005<120)? I must have something like hello <img src=/img/005.gif> goodbye
In two steps to show process
var str = "hello #005 goodbye",
num = str.match(/\#(\d+) /)[1],
gif = '<img src="/img/'+num+'.gif" />';
console.log(str.replace("#"+num,gif));
One step - test for 3 digits too
var str = "hello #005 goodbye"
.replace(/\#(\d{3})/,'<img src="/img/$1.gif" />');
console.log(str);
With test:
function addGif(str) {
var num = str.match(/\#(\d+)/),
gif = num &&
num.length > 0 &&
parseInt(num[1]) >= 5 &&
parseInt(num[1]) <= 120 ? '<img src="/img/' + num[1] + '.gif" />' : "";
return gif ? str.replace("#" + num[1], gif) : "no number or number not in range";
}
var str = "hello # goodbye"; // will not return a match
console.log(addGif(str))
str = "hello #" // will not return a match
console.log(addGif(str))
str = "hello #005" // will return a match
console.log(addGif(str))
str = "hello #1005" // will not return a match
console.log(addGif(str))
str = "hello #100" // will return a match
console.log(addGif(str))
str = "hello #1111111111 goodbye" // will not return a match
console.log(addGif(str))
Makes no sense to do it in two steps when you can do it in one. The capture group in replace is $1 so you put that where you want the number to go.
var str = "hello #005 goodbye",
result = str.replace(/#(\d+)/,'<img src="/img/$1.gif" />');
console.log(result);
With a check inside the replace with the number requirement I missed the 2 times I read the question!
var str = "hello #005 goodbye",
result = str.replace(/#(\d{3})/, function (x, group1) {
var num = parseInt(group1);
return num >= 5 && num<=120 ? '<img src="/img/' + group1 + '.gif" />' : group1;
});
console.log(result);

how to replace all special characters except for spaces, . and brackets using java script

I am trying to replace all the special characters in a form in BPM.
I have used
replace(/[_\W]+/g, "-")
but this replaces all including .,() and spaces. I need to exclude some of these characters from being replaced
this is what i am trying to do in BPM
tw.local.sql="insert into BPM_RBD_GATEWAY values ('Forwarded','"+tw.local.RBDG.ProcessID+"','"+tw.local.RBDG.SolID+"','"+tw.local.RBDG.BranchCode+"','"+tw.local.RBDG.BranchName.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Name_brwr.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Name_Cooblgnt.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.CustID_Exstng.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.D_Status_Loan.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.D_Internl_Crdt_Ratng+"','"+tw.local.RBDG.D_Scheme_ProdctType.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Acnt_Nmbr.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Loan_Amnt.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Bal_Outstandng.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Sanctnd_Period.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Deviatns_loan_sanctnIfany.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.D_Loan_Sourcng+"','"+tw.local.RBDG.Prevs_Rate_concsn.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.D_Existng_Accnt_Type+"','"+tw.local.RBDG.Existing_acnt_Rate.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Recomndr_Rate.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Arrears_Inspctn_Comnts.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.D_Borwr_Source_Empl_Profsn.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Borwr_Source_Details.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Secrty_prmry_Nature.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Secrty_prmry_Value.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Secrty_prmry_DtlsLimit.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Secrty_Collatrl_Nature.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Secrty_Collatrl_Value.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Secrty_Collatrl_DetLimt.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Deatils_ExistngBus_BrwrEnjoy.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Deatils_ExistngBus_TotGroup.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Deatils_ExistngBus_OprtvAccnt.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Deatils_ExistngBus_OtherPrdct.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Additional_Details.replace(/[_\W]+/g, "-")+"','"+tw.local.RBDG.Specific_BrRecom.replace(/[_\W]+/g, "-")+"','','','','','','','','','','','','','','','','','"+tw.local.RBDG.Br_Entry_User+"','"+tw.local.RBDG.Recomndr_Entry_User+"','','','','','','','','','"+tw.local.RBDG.Date+"','','','','','','','')";
Use replacer function to filter out matches which you don't want to replace
var excludes = [",", " ", "(", ")"];
var output = input.replace(/[_\W]/g, function(match){
if ( excludes.indexOf(match) == -1 )
{
match = "-";
}
return match;
}) ;
DEMO
var input = "asda<>*(*_()(), wdsf %^&%^&";
var excludes = [",", " ", "(", ")"];
var output = input.replace(/[_\W]/g, function(match){
if ( excludes.indexOf(match) == -1 )
{
match = "-";
}
return match;
}) ;
alert(output);
var str = "ABC/D A.b.c.;Qwerty(dgdf)";
var result = str.replace(/[^A-Za-z.;()]/g, "");
You'll end up with ABCDA.b.c.;Qwerty(dgdf)
Tell me if that worked out well for you

Formatting number as thousand using only Javascript

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/

how to get selected text surrounding context in javascript in different paragraph?

hi I have a few problems:
What might I get the word around the word selected, if the word before and after the selected word given limits only 20 words that surround the selected word?
how to get the correct position if the word in a paragraph have the same word, for example I have a sentence like this: foo laa foo doo then I choose the word "foo" whose position is in between the words laa and doo?
how to get word from a different paragraph?
for example:
p1 : I like the red shirt
p2: my mother did not like the red shirt
the word I selected is "mother", and I have to take 10 words around the word "mother" that is "I like the red dress" and "I do not like the red shirt."
notes:
question No. 2 is able to use the nextSibling and previousSibling?
this is my code i try :
<html>
<head>
<script type="text/javascript">
function getElements(){
var x = document.getElementsByTagName("body");
x = x[0].innerHTML;
x = x.replace(/&(lt|gt);/g, function (strMatch, p1){
return (p1 == "lt")? "<" : ">";});
var str = x.replace(/<\/?[^>]+(>|$)/g, "");
var emailPattern = /[_a-zA-Z0-9\.]+#[\.a-zA-Z0-9]+\.[a-zA-Z]+/gi;
var urlPattern = /[a-z]+:\/\/[^\s]+/gi;
var numberOrSymbolPattern = /[0-9\.,!##\$%\^\&*\(\)`~_\-=\+|\\{}\[\]\s:;<>\?\/]+/gi;
//////alert(str);
var str = str.replace(emailPattern , " ");
var str = str.replace(urlPattern , " ");
var str = str.replace(numberOrSymbolPattern , " ");
//////alert(str);
var str = str.replace(/[\n\f\r\t]/g, " ");
var hilangtandabaca = str.replace(/[.!:;'",?]/g," ");
var kataptg = hilangtandabaca;
//alert(kataptg);
var kata = new Array();
kata[0] = " is ";
kata[1] = " the ";
kata[3] = " of ";
kata[4] = " a ";
kata[5] = " or ";
kata[6] = " for ";
kata[7] = " from ";
kata[8] = " in ";
kata[9] = " this ";
kata[10] = " and ";
kata[11] = " on ";
kata[12] = " with ";
kata[13] = " my ";
for(var i=0,regex; i<kata.length; i++){
var regex = new RegExp(kata[i],"gi");
kataptg = kataptg.replace(regex," ");
}
var select = getSelected()+ "";
alert(select);
var index = kataptg.indexOf(select);
//alert("indeks select text:" + index);
if (index >= 0) {
var strBefore = "";
var strAfter = "";
//var strOri ="";
//if (index = -1)
//strOri = kataptg.substr(index);
//alert(strOri);
if (index > 0)
strBefore = kataptg.substr(0, index);
//alert(strBefore);
if (index < kataptg.length - 1)
strAfter = kataptg.substr(index + select.length, kataptg.length - (index + select.length));
//alert(strAfter);
alert("Before: " + strBefore + "\nAfter: " + strAfter);
}
}
function getSelected() {
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
} else if (document.selection) {
userSelection = document.selection.createRange();
}
return userSelection;
}
</script>
</head>
<body>
<h2>About</h2>
<p> my email : a#a.a
<p> my url http://id.wikipedia.org/wiki/URL
<p> my telepon number = 081330782
<p>okey In agriculture, the harvest is the process of gathering mature crops from the fields. Reaping is the cutting of grain or pulse for harvest, typically using a scythe, sickle, or reaper.[1] The harvest marks the end of the growing season, or the growing cycle for a particular crop, and this is the focus of seasonal celebrations of on many religions. On smaller farms with minimal mechanization, harvesting is the most labor-intensive activity of the growing season great yeah. !:;'",?</p>
<p>
<input type="button" onclick="getElements()" value="ambil select text" />
</p>
</body>
</html>
This is a perfect example of JavaScript's innerHTML and split() methods. You can loop through the content of all of the p elements. Here's an example of searching in the first paragraph:
contentArray = document.getElementByTagName('p')[0].innerHTML.split(' ')
split(' ') splits the content of the element into an array, separating by the spaces. innerHTML is self explanatory.
Now, to find your words. indexOf() is your friend in this case:
foodex = contentArray.indexOf('foo');
alert('The first occurrence of the string \'foo\' in the text is at word number ' + foodex);
Finally, to get surrounding words, just play with the array (this won't work if the occurrence of the string is close to the start or end of the paragraph, namely less than 10 words away:
alert('I am the 10th word after \'foo\'' + contentArray[foodex + 10 - 1]);
Good luck (no guarantees this code works out of the box)!

Categories