javascript converting strings from gbk to utf-8 - javascript

I got text from internet with node.js and want to convert it from gbk encoding to utf-8.
I tried to the node-iconv module, it didn't work.
var Iconv = require('iconv').Iconv;
var gbk_to_utf8 = new Iconv('gbk', 'utf-8');
var b = gbk_to_utf8.convert(new Buffer(body.toString()));
console.log(b.toString());

Try this code from this link:
GB2312UTF8 = {
Dig2Dec : function(s){
var retV = 0;
if(s.length == 4){
for(var i = 0; i < 4; i ++){
retV += eval(s.charAt(i)) * Math.pow(2, 3 - i);
}
return retV;
}
return -1;
} ,
Hex2Utf8 : function(s){
var retS = "";
var tempS = "";
var ss = "";
if(s.length == 16){
tempS = "1110" + s.substring(0, 4);
tempS += "10" + s.substring(4, 10);
tempS += "10" + s.substring(10,16);
var sss = "0123456789ABCDEF";
for(var i = 0; i < 3; i ++){
retS += "%";
ss = tempS.substring(i * 8, (eval(i)+1)*8);
retS += sss.charAt(this.Dig2Dec(ss.substring(0,4)));
retS += sss.charAt(this.Dig2Dec(ss.substring(4,8)));
}
return retS;
}
return "";
} ,
Dec2Dig : function(n1){
var s = "";
var n2 = 0;
for(var i = 0; i < 4; i++){
n2 = Math.pow(2,3 - i);
if(n1 >= n2){
s += '1';
n1 = n1 - n2;
}
else
s += '0';
}
return s;
},
Str2Hex : function(s){
var c = "";
var n;
var ss = "0123456789ABCDEF";
var digS = "";
for(var i = 0; i < s.length; i ++){
c = s.charAt(i);
n = ss.indexOf(c);
digS += this.Dec2Dig(eval(n));
}
return digS;
},
GB2312ToUTF8 : function(s1){
var s = escape(s1);
var sa = s.split("%");
var retV ="";
if(sa[0] != ""){
retV = sa[0];
}
for(var i = 1; i < sa.length; i ++){
if(sa[i].substring(0,1) == "u"){
//alert(this.Str2Hex(sa[i].substring(1,5)));
retV += this.Hex2Utf8(this.Str2Hex(sa[i].substring(1,5)));
if(sa[i].length){
retV += sa[i].substring(5);
}
}
else{
retV += unescape("%" + sa[i]);
if(sa[i].length){
retV += sa[i].substring(5);
}
}
}
return retV;
},
UTF8ToGB2312 : function(str1){
var substr = "";
var a = "";
var b = "";
var c = "";
var i = -1;
i = str1.indexOf("%");
if(i==-1){
return str1;
}
while(i!= -1){
if(i<3){
substr = substr + str1.substr(0,i-1);
str1 = str1.substr(i+1,str1.length-i);
a = str1.substr(0,2);
str1 = str1.substr(2,str1.length - 2);
if(parseInt("0x" + a) & 0x80 == 0){
substr = substr + String.fromCharCode(parseInt("0x" + a));
}
else if(parseInt("0x" + a) & 0xE0 == 0xC0){ //two byte
b = str1.substr(1,2);
str1 = str1.substr(3,str1.length - 3);
var widechar = (parseInt("0x" + a) & 0x1F) << 6;
widechar = widechar | (parseInt("0x" + b) & 0x3F);
substr = substr + String.fromCharCode(widechar);
}
else{
b = str1.substr(1,2);
str1 = str1.substr(3,str1.length - 3);
c = str1.substr(1,2);
str1 = str1.substr(3,str1.length - 3);
var widechar = (parseInt("0x" + a) & 0x0F) << 12;
widechar = widechar | ((parseInt("0x" + b) & 0x3F) << 6);
widechar = widechar | (parseInt("0x" + c) & 0x3F);
substr = substr + String.fromCharCode(widechar);
}
}
else {
substr = substr + str1.substring(0,i);
str1= str1.substring(i);
}
i = str1.indexOf("%");
}
return substr+str1;
}
};
And to test the function:
GBK => UTF8:
var utf8 = GB2312UTF8.GB2312ToUTF8("中文GB2312");
UTF8 => GBK:
GB2312UTF8.UTF8ToGB2312(utf8);

Related

Converting unary string of units to binary string only works once (Javascript)

I built an integer conversation from unary string of units = '1' to a binary representation in string format!
The function only works once and is limited to the number 31
here is my approach in javascript - can you help or explain?
func_unary_to_digit = function(p_reg1) {
var grouper = {
group:''
};
var unit = '1';
var p_sys = 2;
var i_grp = 0;
var t1_reg = p_reg1;
var lw1_unary = '';
var rw1_unary = '';
var lw2_unary = '0';
var rw2_unary = '';
for(it_g = 0; it_g < p_sys; it_g++) {
grouper.group += unit;
}
if(p_reg1.length === 1) {
lw1_unary = '';
rw1_unary = unit;
} else {
for (it_s = 0; it_s <= t1_reg.length; it_s++) {
lw1_unary = '';
i_grp = 0;
for (it_c = 0; it_c < t1_reg.length; it_c++) {
if (it_c % grouper.group.length === 1) {
lw1_unary += unit;
i_grp++;
}
}
if (t1_reg.length % grouper.group.length === 0) {
//rw1_unary += inf;
rw1_unary += '0';
}
if (t1_reg.length % grouper.group.length === 1) {
rw1_unary += unit;
}
if (lw1_unary.length === 1) {
lw1_unary = '';
rw1_unary += unit;
}
t1_reg = lw1_unary;
}
}
rw1_unary = rw1_unary.split('').reverse().join('');
console.log(rw1_unary);
}

How to pass document from JSOUP to a webview and run a script

I want to access a website with jsoup, but it has a protection that is evaluated by a script. I want to know how I can get the value of ASP.KLR
"ASP.KLR =" + toHex (slowAES.decrypt (c, 2, a, b))
When I make the Jsoup request, it returns the following code
"<body>\n" +
" <div class=\"lds-grid\"> \n" +
" <div></div> \n" +
" <div></div> \n" +
" <div></div> \n" +
" <div></div> \n" +
" <div></div> \n" +
" <div></div> \n" +
" <div></div> \n" +
" <div></div> \n" +
" <div></div>\n" +
" </div> \n" +
" <script type=\"text/javascript\" src=\"https://enlineaplus.fcs-tech.com/public/js/aes.min.js\"></script>\n" +
" <script> function toNumbers(d) { var e = []; d.replace(/(..)/g, function (d) { e.push(parseInt(d, 16)); }); return e; } function toHex() { for ( var d = [], d = 1 == arguments.length && arguments[0].constructor == Array ? arguments[0] : arguments,e = \"\",f = 0;f < d.length;f++ )e += (16 > d[f] ? \"0\" : \"\") + d[f].toString(16); return e.toLowerCase(); } var a = toNumbers(\"d68d69a9a746d20032277ede658ba3ad\"), b = toNumbers(\"58c9e810e2ebcc49ae9ee28af1c6dd53\"), c = toNumbers(\"6cecb0d0211b3c563a23ae1f1b00d5a0\"); document.cookie = \"ASP.KLR=\" + toHex(slowAES.decrypt(c, 2, a, b)) + \"; expires=Session; path=/\";</script>\n" +
" </body>";
That document I want to pass it to a webview and get the value, any ideas
You'll have to solve it. You won get that value with an httpClient. I've already done this in Flutter, just do the same in your language.
Any doubt write to telegram #ernestoaqs.
var href = AesEncrypt.getLocationHrefFromKLR(response.data.toString());
var a = AesEncrypt.getAFromScriptPage(response.data.toString());
var b = AesEncrypt.getBFromScriptPage(response.data.toString());
var c = AesEncrypt.getCFromScriptPage(response.data.toString());
var klrCookieString = AesEncrypt.getCookieKLR(a, b, c);
The class would then be:
class AesEncrypt {
static final key = encrypting.Key.fromLength(32);
static final iv = encrypting.IV.fromLength(16);
static final encrypter = encrypting.Encrypter(AES(key, mode: AESMode.cbc));
static int _hexToInt(String hex) {
int val = 0;
int len = hex.length;
for (int i = 0; i < len; i++) {
int hexDigit = hex.codeUnitAt(i);
if (hexDigit >= 48 && hexDigit <= 57) {
val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
} else if (hexDigit >= 65 && hexDigit <= 70) {
val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
} else if (hexDigit >= 97 && hexDigit <= 102) {
val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
} else {
throw new FormatException("Invalid hexadecimal value");
}
}
return val;
}
static toNumbers(String texto) {
int indexInit = 0;
int indexEnd = 2;
List<int> arr = [];
while (indexEnd <= texto.length) {
arr.add(_hexToInt(texto.substring(indexInit, indexEnd)));
indexInit += 2;
indexEnd += 2;
}
return arr;
}
static getAFromScriptPage(String html) {
String regexStringForA = r'var a = toNumbers\("([a-z0-9]+)"';
RegExp regExpA = new RegExp(regexStringForA);
var matchesA = regExpA.allMatches(html);
var matchA = matchesA.elementAt(0);
return matchA.group(1);
}
static getBFromScriptPage(String html) {
String regexStringForB = r'b = toNumbers\("([a-z0-9]+)"';
RegExp regExpB = new RegExp(regexStringForB);
var matchesB = regExpB.allMatches(html);
var matchB = matchesB.elementAt(0);
return matchB.group(1);
}
static getCFromScriptPage(String html) {
String regexStringForC = r'c = toNumbers\("([a-z0-9]+)"';
RegExp regExpC = new RegExp(regexStringForC);
var matchesC = regExpC.allMatches(html);
var matchC = matchesC.elementAt(0);
return matchC.group(1);
}
static getLocationHrefFromKLR(String html) {
String regexStringForC =
r'location.href[ ]?=[ ]?"([. ?\%\#\#\^\-_\*\=\&a-zA-Z0-9:\/\/]+)';
RegExp regExp = new RegExp(regexStringForC);
var matches = regExp.allMatches(html);
var match = matches.elementAt(0);
return match.group(1);
}
static getCookieKLR(aa, bb, cc) {
var a = toNumbers(aa); // key
var b = toNumbers(bb); // iv
var c = toNumbers(cc); // text
Uint8List key = Uint8List.fromList(a);
Uint8List iv = Uint8List.fromList(b);
Uint8List srcData = Uint8List.fromList(c);
var crypt = AesCrypt();
AesMode mode = AesMode.cbc;
crypt.aesSetKeys(key, iv);
crypt.aesSetMode(mode);
Uint8List decryptedData = crypt.aesDecrypt(srcData);
String result = "";
decryptedData.forEach((element) {
if (element.toRadixString(16).length == 1) {
result += "0";
}
result += "${element.toRadixString(16)}";
});
return result;
}
}

Encrypt and decrypt a string using simple Javascript without using any external library

I want to create a function to encrypt a string which will shorten the string into alphanumeric character and also create a function decrypt which will get back the encrypted string.
Here is what I coded by taking reference online.
function compress(string) {
string = unescape(encodeURIComponent(string));
var newString = '',
char, nextChar, combinedCharCode;
for (var i = 0; i < string.length; i += 2) {
char = string.charCodeAt(i);
if ((i + 1) < string.length) {
nextChar = string.charCodeAt(i + 1) - 31;
combinedCharCode = char + "" + nextChar.toLocaleString('en', {
minimumIntegerDigits: 2
});
newString += String.fromCharCode(parseInt(combinedCharCode, 10));
} else {
newString += string.charAt(i);
}
}
return newString;
}
function decompress(string) {
var newString = '',
char, codeStr, firstCharCode, lastCharCode;
for (var i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (char > 132) {
codeStr = char.toString(10);
firstCharCode = parseInt(codeStr.substring(0, codeStr.length - 2), 10);
lastCharCode = parseInt(codeStr.substring(codeStr.length - 2, codeStr.length), 10) + 31;
newString += String.fromCharCode(firstCharCode) + String.fromCharCode(lastCharCode);
} else {
newString += string.charAt(i);
}
}
return newString;
}
var stringToCompress = 'awesome';
var compressedString = compress(stringToCompress);
var decompressedString = decompress(compressedString);
console.log("encrypted :",compressedString);
console.log("decrypted :",decompressedString);
Currently the output from the sting="awesome" is
encrypted: ☼⟈⮪e
decrypted: awesome
I want similar encryption but must be only in alphanumeric values and not symbols.
I don't know what is your goal (is it make the string shorter, but binary or encrypted and in ascii range), so if it's the later, than you could use base64 encoding:
function compress(string) {
string = unescape(encodeURIComponent(string));
var newString = '',
char, nextChar, combinedCharCode;
for (var i = 0; i < string.length; i += 2) {
char = string.charCodeAt(i);
if ((i + 1) < string.length) {
nextChar = string.charCodeAt(i + 1) - 31;
combinedCharCode = char + "" + nextChar.toLocaleString('en', {
minimumIntegerDigits: 2
});
newString += String.fromCharCode(parseInt(combinedCharCode, 10));
} else {
newString += string.charAt(i);
}
}
return btoa(unescape(encodeURIComponent(newString)));
}
function decompress(string) {
var newString = '',
char, codeStr, firstCharCode, lastCharCode;
string = decodeURIComponent(escape(atob(string)));
for (var i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (char > 132) {
codeStr = char.toString(10);
firstCharCode = parseInt(codeStr.substring(0, codeStr.length - 2), 10);
lastCharCode = parseInt(codeStr.substring(codeStr.length - 2, codeStr.length), 10) + 31;
newString += String.fromCharCode(firstCharCode) + String.fromCharCode(lastCharCode);
} else {
newString += string.charAt(i);
}
}
return newString;
}
var stringToCompress = 'awesome';
var compressedString = compress(stringToCompress);
var decompressedString = decompress(compressedString);
console.log("encrypted :",compressedString);
console.log("decrypted :",decompressedString);
Or if you trully want alphanumerical, than you can simply convert it into HEX:
function compress(string) {
string = unescape(encodeURIComponent(string));
var newString = '',
char, nextChar, combinedCharCode;
for (var i = 0; i < string.length; i += 2) {
char = string.charCodeAt(i);
if ((i + 1) < string.length) {
nextChar = string.charCodeAt(i + 1) - 31;
combinedCharCode = char + "" + nextChar.toLocaleString('en', {
minimumIntegerDigits: 2
});
newString += String.fromCharCode(parseInt(combinedCharCode, 10));
} else {
newString += string.charAt(i);
}
}
return newString.split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"");
}
function decompress(string) {
var newString = '',
char, codeStr, firstCharCode, lastCharCode;
string = string.match(/.{1,4}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"");
for (var i = 0; i < string.length; i++) {
char = string.charCodeAt(i);
if (char > 132) {
codeStr = char.toString(10);
firstCharCode = parseInt(codeStr.substring(0, codeStr.length - 2), 10);
lastCharCode = parseInt(codeStr.substring(codeStr.length - 2, codeStr.length), 10) + 31;
newString += String.fromCharCode(firstCharCode) + String.fromCharCode(lastCharCode);
} else {
newString += string.charAt(i);
}
}
return newString;
}
var stringToCompress = 'awesome';
var compressedString = compress(stringToCompress);
var decompressedString = decompress(compressedString);
console.log("encrypted :",compressedString);
console.log("decrypted :",decompressedString);

How to infinity spin on slot machine jQuery and stop it after do some action?

I have 2 option in radio input
Tab screen to stop in 0.5 sec -> So I complete this solution.
Tab screen to stop immediately. I want it spin after I press the submit button and it stops after I tab the screen.
Here is my fiddle here: https://jsfiddle.net/7det89o6/3/
$("#submit-btn").click(function() {
var cond = valRadioFunc();
if (cond == 1) {
$('.reel-container:first').slotMachine('00' + 1).toString();
// one click
$(".bg-img").one("click", function() {
$('.reel-container:first').slotMachine(randGen());
});
} else if (cond == 2) {
$('.reel-container:first').slotMachine('00' + 1).toString();
}
});
}
<script type="text/javascript">
var reeling_time = 500;
var stop_spinning_time_difference = 350;
var start_spinning_time = 0;
var currency_symbol = "$";
var isInfinity = false;
$(document).ready(function() {
$(document).on('show.bs.modal', '.modal', function() {
function valRadioFunc() {
var valRadio = $('input[name=radio]:checked', '#form-select').val();
return valRadio;
}
$("#submit-btn").click(function() {
var cond = valRadioFunc();
if (cond == 1) {
$('.reel-container:first').slotMachine('00' + 1).toString();
// one click
$(".bg-img").one("click", function() {
isInfinity = false;
$('.reel-container:first').slotMachine(randGen());
});
} else if (cond == 2) {
$('.reel-container:first').slotMachine('00' + 1).toString();
isInfinity = true;
// one click
$(".bg-img").one("click", function() {
reeling_time = 0;
isInfinity = false;
$('.reel-container:first').slotMachine(randGen());
});
}
});
});
});
function randGen() {
var minRange = 1;
var maxRange = 999;
var randNum = (Math.floor(Math.random() * maxRange) + minRange).toString();
if (randNum.toString().length == 3) {
return randNum;
} else if (randNum.toString().length == 2) {
return "0" + randNum;
} else if (randNum.toString().length == 1) {
reeling_time = 0;
return "00" + randNum;
}
}
function collision($div1, $div2) {
var x1 = $div1.offset().left;
var w1 = 40;
var r1 = x1 + w1;
var x2 = $div2.offset().left;
var w2 = 40;
var r2 = x2 + w2;
if (r1 < x2 || x1 > r2) return false;
return true;
}
$.fn.slotMachine = function(my_number) {
var $parentSlot = this;
var hidden_reels_html = '';
var hidden_reels_array = [];
var numberFormat = function number_format(number) {
number = (number + '');
return number;
}
for (var $j = 0; $j <= 9; $j++) {
hidden_reels_array[$j] = "";
for (var $i = 0; $i <= 9; $i++) {
hidden_reels_array[$j] += '<div class="reel-symbol' + ($i == 0 ? ' reel-loop' : '') + '">' + (($j + $i) % 10) + '</div>';
}
}
var transformNumberToArrayPlusDollar = function(my_number) {
var my_scale = parseInt(my_number, 10) > 999 ? 0 : 2;
my_number = numberFormat(my_number, my_scale, ".", ",");
var my_number_array = my_number.split('');
// my_number_array.unshift(currency_symbol);
return my_number_array;
};
//Effect for the reel to go up and then down like it is pushed to spin
var effectBeforeSpin = function() {
$parentSlot.find('.main-reel-symbol').removeClass('reel-stop').addClass('reel-begin');
};
var slotMachine = function(my_number) {
var my_number_array = transformNumberToArrayPlusDollar(my_number);
var reels_html = '';
for (var $i = 0; $i < my_number_array.length; $i++) {
reels_html += '<div class="reel">' + hidden_reels_array[($i % 10)] + '</div>';
}
effectBeforeSpin();
var startSpinning = function() {
$parentSlot.html(reels_html);
var my_timer = reeling_time;
$.each(my_number_array, function(my_index, my_value) {
var next_value = /^[0-9]$/.test(my_value) ? (parseInt(my_value, 10) + 1) % 10 : "0";
var stopSpinning = function() {
$parentSlot.find('.reel:eq(' + my_index + ')')
.html("<div class='reel-symbol main-reel-symbol reel-stop'>" + my_value + "</div>")
.append("<div class='reel-symbol'>" + next_value + "</div>");
};
if(!isInfinity){
setTimeout(stopSpinning, my_timer);
}
my_timer += stop_spinning_time_difference;
});
};
setTimeout(startSpinning, start_spinning_time);
};
slotMachine(my_number);
return this;
};
$('.reel-container:first').slotMachine('00' + 1).toString();
</script>
I add one variable at top of JavaScript code.

Formatting the phone number for multiple asp:TextBox in Javascript

This might be very basic problem. I found the similar solution on Stack Overflow for formatting the phone number and I used it for asp:TextBox control, but I want this code to be work for multiple phone number textbox control rather than passing IDs directly. I have five different phone field and all those textbox are asp:TextBox. I want to call the same code from all those filed. (I am looking this solution in JavaScript only)
Here is my JS code:
/*Start of phone number formating */
var n;
var p;
var p1;
function format_phone() {
p = p1.value
if (p.length == 3) {
pp = p;
d4 = p.indexOf('(')
d5 = p.indexOf(')')
if (d4 == -1) {
pp = "(" + pp;
}
if (d5 == -1) {
pp = pp + ") ";
}
document.getElementById('<%=HomePhone.ClientID%>').value = "";
document.getElementById('<%=HomePhone.ClientID%>').value = pp;
}
if (p.length > 3) {
d1 = p.indexOf('(')
d2 = p.indexOf(')')
if (d2 == -1) {
l30 = p.length;
p30 = p.substring(0, 4);
p30 = p30 + ") "
p31 = p.substring(5, l30);
pp = p30 + p31;
document.getElementById('<%=HomePhone.ClientID%>').value = "";
document.getElementById('<%=HomePhone.ClientID%>').value = pp;
}
}
if (p.length > 7) {
p11 = p.substring(d1 + 1, d2);
if (p11.length > 4) {
p12 = p11;
l12 = p12.length;
l15 = p.length
p13 = p11.substring(0, 4);
p14 = p11.substring(4, l12);
p15 = p.substring(d2 + 1, l15);
document.getElementById('<%=HomePhone.ClientID%>').value = "";
pp = "(" + p13 + ") " + p14 + p15;
document.getElementById('<%=HomePhone.ClientID%>').value = pp;
}
l16 = p.length;
p16 = p.substring(d2 + 2, l16);
l17 = p16.length;
if (l17 > 3 && p16.indexOf('-') == -1) {
p17 = p.substring(d2 + 1, d2 + 5);
p18 = p.substring(d2 + 5, l16);
p19 = p.substring(0, d2 + 1);
pp = p19 + p17 + "-" + p18;
document.getElementById('<%=HomePhone.ClientID%>').value = "";
document.getElementById('<%=HomePhone.ClientID%>').value = pp;
}
}
setTimeout(format_phone, 100)
}
function getIt(m) {
n = m.name;
p1 = m;
format_phone()
}
/* End of phone number formating */
and asp:TextBox as
<asp:TextBox MaxLength="14"
runat="server" ID="HomePhone"
placeholder="(xxx) xxx-xxxx"
onFocus="if(this.value==this.defaultValue)this.value='';" onclick="javascript:getIt(this)"
onkeypress='return event.charCode >= 48 && event.charCode <= 57'/>
And I have other similar four textboxes for phone field and I want to use the same formatting logic for all those. What is the best way to use this or any alternative JavaScript code from multiple textbox. Any help would be highly appreciated.
I don't remember where I found this solution but, it might help you out to format the phone fields:
<script type="text/javascript">
//Phone validation
var zChar = new Array(' ', '(', ')', '-', '.');
var maxphonelength = 13;
var phonevalue1;
var phonevalue2;
var cursorposition;
function ParseForNumber1(object) {
phonevalue1 = ParseChar(object.value, zChar);
}
function ParseForNumber2(object) {
phonevalue2 = ParseChar(object.value, zChar);
}
function backspacerUP(object, e) {
if (e) {
e = e
} else {
e = window.event
}
if (e.which) {
var keycode = e.which
} else {
var keycode = e.keyCode
}
ParseForNumber1(object)
if (keycode >= 48) {
ValidatePhone(object)
}
}
function backspacerDOWN(object, e) {
if (e) {
e = e
} else {
e = window.event
}
if (e.which) {
var keycode = e.which
} else {
var keycode = e.keyCode
}
ParseForNumber2(object)
}
function GetCursorPosition() {
var t1 = phonevalue1;
var t2 = phonevalue2;
var bool = false
for (i = 0; i < t1.length; i++) {
if (t1.substring(i, 1) != t2.substring(i, 1)) {
if (!bool) {
cursorposition = i
bool = true
}
}
}
}
function ValidatePhone(object) {
var p = phonevalue1
p = p.replace(/[^\d]*/gi, "")
if (p.length < 3) {
object.value = p
} else if (p.length == 3) {
pp = p;
d4 = p.indexOf('(')
d5 = p.indexOf(')')
if (d4 == -1) {
pp = "(" + pp;
}
if (d5 == -1) {
pp = pp + ")";
}
object.value = pp;
} else if (p.length > 3 && p.length < 7) {
p = "(" + p;
l30 = p.length;
p30 = p.substring(0, 4);
p30 = p30 + ")"
p31 = p.substring(4, l30);
pp = p30 + p31;
object.value = pp;
} else if (p.length >= 7) {
p = "(" + p;
l30 = p.length;
p30 = p.substring(0, 4);
p30 = p30 + ")"
p31 = p.substring(4, l30);
pp = p30 + p31;
l40 = pp.length;
p40 = pp.substring(0, 8);
p40 = p40 + "-"
p41 = pp.substring(8, l40);
ppp = p40 + p41;
object.value = ppp.substring(0, maxphonelength);
}
GetCursorPosition()
if (cursorposition >= 0) {
if (cursorposition == 0) {
cursorposition = 2
} else if (cursorposition <= 2) {
cursorposition = cursorposition + 1
} else if (cursorposition <= 5) {
cursorposition = cursorposition + 2
} else if (cursorposition == 6) {
cursorposition = cursorposition + 2
} else if (cursorposition == 7) {
cursorposition = cursorposition + 4
e1 = object.value.indexOf(')')
e2 = object.value.indexOf('-')
if (e1 > -1 && e2 > -1) {
if (e2 - e1 == 4) {
cursorposition = cursorposition - 1
}
}
} else if (cursorposition < 11) {
cursorposition = cursorposition + 3
} else if (cursorposition == 11) {
cursorposition = cursorposition + 1
} else if (cursorposition >= 12) {
cursorposition = cursorposition
}
var txtRange = object.createTextRange();
txtRange.moveStart("character", cursorposition);
txtRange.moveEnd("character", cursorposition - object.value.length);
txtRange.select();
}
}
function ParseChar(sStr, sChar) {
if (sChar.length == null) {
zChar = new Array(sChar);
}
else zChar = sChar;
for (i = 0; i < zChar.length; i++) {
sNewStr = "";
var iStart = 0;
var iEnd = sStr.indexOf(sChar[i]);
while (iEnd != -1) {
sNewStr += sStr.substring(iStart, iEnd);
iStart = iEnd + 1;
iEnd = sStr.indexOf(sChar[i], iStart);
}
sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);
sStr = sNewStr;
}
return sNewStr;
}
</script>
And call this on your asp:TextBox as
<asp:TextBox MaxLength="14"
runat="server" ID="HomePhone"
placeholder="(xxx) xxx-xxxx"
onkeydown="javascript:backspacerDOWN(this,event);"
onkeyup="javascript:backspacerUP(this,event);" />
And If you want to insert space after ')' you can use the following trick
function markSpace(field) {
if (field.value.includes(")")) {
field.value = field.value.split(')').join(') ');
}
if (field.value.includes(") ")) {
field.value = field.value.replace(/ +/g, ' ');
}
}
and call this as onblur="markSpace(this);" But I personally prefer using JQuery :)

Categories