JavaScript: count minimal length of characters in text, ignoring special codes inside
I want to ignore counting the length of characters in the text if there are special codes inside in textarea. I mean not to count the special codes characters in the text. I use special codes to define inputing smileys in the text. I want to count only the length of the text ignoring special code.
Here is my approximate code I tried to write, but can't let it work:
// smileys
// =======
function smileys(){
var smile = new Array();
smile[0] = "[:rolleyes:]";
smile[1] = "[:D]";
smile[2] = "[:blink:]";
smile[3] = "[:unsure:]";
smile[4] = "[8)]";
smile[5] = "[:-x]";
return(smile);
}
// symbols length limitation
// =========================
function minSymbols(field){
var get_smile = smileys();
var text = field.value;
for(var i=0; i<get_smile.length; i++){
for(var j=0; j<(text.length); j++){
if(get_smile[i]==text[j]){
text = field.value.replace(get_smile[i],"");
}
}
}
if(text.length < 50){
document.getElementById("saveB").disabled=true;
} else {
document.getElementById("saveB").disabled=false;
}
}
How the script should be in order to l开发者_StackOverflow中文版et it work? Thank you!
I'd start by changing how I define the smilies:
var smilies = [
{text: "[:rolleyes:]", exp: /\[\:rolleyes\:\]/g},
{text: "[:D]", exp: /\[\:D\]/g},
{text: "[:blink:]", exp: /\[\:blink\:\]/g},
{text: "[:unsure:]", exp: /\[\:unsure\:\]/g},
{text: "[8)]", exp: /\[8\)\]/g},
{text: "[:-x]", exp: /\[\:-x\]/g}
];
(I didn't immediately see any reason this had to be a function, but you can make it one if you want.) That's an array of objects, each object having a text
property with the smiley text and an exp
object with a RegExp that would match it (with the global flag set).
Then the function looks a bit like this:
function getLengthMinusSmilies(field) {
var text, index, length, smiley;
text = field.value;
length = text.length;
for (index = 0; index < smilies.length; ++index) {
smiley = smilies[index];
while (smiley.exp.test(text)) {
length -= smiley.text.length;
}
}
return length;
}
That avoids creating and throwing away temporary strings. It just counts matches of smilies and disregards their length.
You don't have to use objects with text
and exp
values, you can use paralle arrays if you like:
var smilies = [
"[:rolleyes:]",
"[:D]",
"[:blink:]",
"[:unsure:]",
"[8)]",
"[:-x]"
];
var matchExps = [
/\[\:rolleyes\:\]/g,
/\[\:D\]/g,
/\[\:blink\:\]/g,
/\[\:unsure\:\]/g,
/\[8\)\]/g,
/\[\:-x\]/g
];
...and then adjust the loop in the function accordingly. Using one array with objects tends to be more maintainable, but if you need an array elsewhere...
function minSymbols(field){
var get_smile = smileys();
var text = field.value;
for(var i=0; i<get_smile.length; i++){
text = text.replace(get_smile[i],"");
}
}
function getTxtLen()
{
var str=document.getElementById('myTxtBox').value;
str=str.replace(/\[:some:\]/g,'');
str=str.replace(/\[:some2:\]/g,'');
alert(str.length);
}
精彩评论