Console Error, need to remove a specific character - javascript

I know the title may be confusing, but my problem seems fairly easy.
I'm trying to remove a specific character "#".
This is how it currently logs (Click Here = Image)
I'm trying to simply remove the "#" character so when it logs to the console it won't have the # in front of the text.
I've tried adding this before the break.
var color = stroke.split("#");
but it didn't work.
Here is my code
xhr = new XMLHttpRequest();
xhr.open("GET", "http://colorillo.com/byjy.inline.svg");
xhr.addEventListener("load", function() {
const xmlDoc = new DOMParser().parseFromString(
this.responseText.trim(),
"image/svg+xml"
);
// Get all polylines as strings
let lines = xmlDoc.getElementsByTagName('polyline');
// Loop over all lines
for(let line of lines) {
// --- OPTIONAL START ---
//See Bruce'es comment (rgb() as output)
let stroke = line.style.stroke;
//let size = line.style.stroke-width; -- Disabled
// --- OR ---
// Loop over all styles of this line (output same as input [hex])
for(let style of line.getAttribute('style').split(';')) {
// Get name & value
let valueOffset = style.indexOf(':');
// Check if name equal to 'stroke'
if(style.substr(0, valueOffset).trim() === 'stroke') {
// Save stroke value
stroke = style.substr(valueOffset + 1).trim();
// Break out of the loop (we don't have to search further)
stroke.split("#"); // Here is what I've tried.
break;
}
}
console.log(stroke)
}
});
xhr.send();

Change stroke.split("#") to
stroke.replace('#','');
This will remove the first '#' in the string.
You can confirm by adding
console.log('BEFORE: '+stroke);
before that line, and
console.log('AFTER: '+stroke);
after it. Then check your console.log output in Dev Tools (or equivalent).

Related

How to get range of custom word in my VS Code Extension?

I want to get the range of a custom word in my VS Code extension, if I hover on it, and if the line of text matches a pattern. This is what I've written so far:
vscode.languages.registerHoverProvider('.mylanguage', {
provideHover(document, position, token) {
// define `hoverRange` somewhere here
const hoverLineText = document.lineAt(position.line).text;
const pattern = new RegExp("\\w+\\s{0,}\\(.{0,}\\s{0,}\\)");
if(pattern.test(hoverLineText)){
hoverRange = document.getWordRangeAtPosition(position, pattern);
}
console.log(hoverRange);
//etc. ...
I am expecting that, if you write in the editor something like myFunction ( ), and you hover on any position of that string (e.g. even on the whitespace), the console will output hoverRange, which will take into account the position of the closing parenthesis ), as well.
However, if I hover on the whitespace, nothing is outputted to the console. Instead, I need to hover on myFunction, so that I can get the whole range of the string.
How can I make my VS Code extension treat myFunction ( ) as one single word?
This works for me:
let disposable3 = vscode.languages.registerHoverProvider('plaintext', {
provideHover(document, position) {
let hoverRange;
const hoverLineText = document.lineAt(position.line).text;
const pattern = new RegExp("\\w+\\s*\\(.*\\s*\\)");
if (pattern.test(hoverLineText)){
hoverRange = document.getWordRangeAtPosition(position, pattern);
if (hoverRange) return new vscode.Hover(document.getText(hoverRange), new vscode.Range(position, position));
else return null;
}
else return null;
}
});
context.subscriptions.push(disposable3);
As you can see the hover works over spaces. But the regex is too lenient so that it does pick up things like
if (asdasdasd)
while(adasd)
since those look like a function calls too.

Unable to Get Output From While Loop in Javascript

I'm working on my final project of the Winter 2017 quarter to demonstrate how to use Regular Expressions in both C# and JavaScript code behind pages. I've got the C# version of my demonstration program done, but the JavaScript version is making me pull what little hair I have left on my head out (no small achievement since I got a fresh buzz cut this morning!). The problem involves not getting any output after applying a Regular Expression in a While loop to get each instance of the expression and printing it out.
On my HTML page I have an input textarea, seven radio buttons, an output textarea, and two buttons underneath (one button is to move the output text to the input area to perform multiple iterations of applying expressions, and the other button to clear all textareas for starting from scratch). Each radio button links to a function that applies a regular expression to the text in the input area. Five of my seven functions work; the sixth is the one I can't figure out, and the seventh is essentially the same but with a slightly different RegEx pattern, so if I fix the sixth function, the seventh function will be a snap.
(I tried to insert/upload a JPG of the front end, but the photo upload doesn't seem to be working. Hopefully you get the drift of what I've set up.)
Here are my problem children from my JS code behind:
// RegEx_Demo_JS.js - code behind for RegEx_Demo_JS
var inputString; // Global variable for the input from the input text box.
var pattern; // Global variable for the regular expression.
var result; // Global variable for the result of applying the regular expression to the user input.
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder()
{
var strings = [];
this.append = function (string)
{
string = verify(string);
if (string.length > 0) strings[strings.length] = string;
}
this.appendLine = function (string)
{
string = verify(string);
if (this.isEmpty())
{
if (string.length > 0) strings[strings.length] = string;
else return;
}
else strings[strings.length] = string.length > 0 ? "\r\n" + string : "\r\n";
}
this.clear = function () { strings = []; };
this.isEmpty = function () { return strings.length == 0; };
this.toString = function () { return strings.join(""); };
var verify = function (string)
{
if (!defined(string)) return "";
if (getType(string) != getType(new String())) return String(string);
return string;
}
var defined = function (el)
{
// Changed per Ryan O'Hara's comment:
return el != null && typeof(el) != "undefined";
}
var getType = function (instance)
{
if (!defined(instance.constructor)) throw Error("Unexpected object type");
var type = String(instance.constructor).match(/function\s+(\w+)/);
return defined(type) ? type[1] : "undefined";
}
}
Within the code of the second radio button (which will be the seventh and last function to complete), I tested the ScriptBuilder with data in a local variable, and it ran successfully and produced output into the output textarea. But I get no output from this next function that invokes a While loop:
function RegEx_Match_TheOnly_AllInstances()
{
inputString = document.getElementById("txtUserInput").value;
pattern = /(\s+the\s+)/ig; // Using an Flag (/i) to select either lowercase or uppercase version. Finds first occurrence either as a standalone word or inside a word.
//result = pattern.exec(inputString); // Finds the first index location
var arrResult; // Array for the results of the search.
var sb = getStringBuilder(); // Variable to hold iterations of the result and the text
while ((arrResult = pattern.exec(inputString)) !==null)
{
sb.appendLine = "Match: " + arrResult[0] ;
}
document.getElementById("txtRegExOutput").value = sb.toString();
/* Original code from C# version:
// string pattern = #"\s+(?i)the\s+"; // Same as above, but using Option construct for case insensitive search.
string pattern = #"(^|\s+)(?i)the(\W|\s+)";
MatchCollection matches = Regex.Matches(userTextInput, pattern);
StringBuilder outputString = new StringBuilder();
foreach (Match match in matches)
{
string outputRegExs = "Match: " + "\"" + match.Value + "\"" + " at index [" + match.Index + ","
+ (match.Index + match.Length) + "]" + "\n";
outputString.Append(outputRegExs);
}
txtRegExOutput.Text = outputString.ToString();
*/
} // End RegEx_Match_The_AllInstances
I left the commented code in to show what I had used in the C# code behind version to illustrate what I'm trying to accomplish.
The test input/string I used for this function is:
Don’t go there. If you want to be the Man, you have to beat The Man.
That should return two hits. Ideally, I want it to show the word that it found and the index where it found the word, but at this point I'd be happy to just get some output showing every instance it found, and then build on that with the index and possibly the lastIndex.
So, is my problem in my While loop, the way I'm applying the StringBuilder, or a combination of the two? I know the StringBuilder code works, at least when not being used in a loop and using some test data from the site I found that code. And the code for simply finding the first instance of "the" as a standalone or inside another word does work and returns output, but that doesn't use a loop.
I've looked through Stack Overflow and several other JavaScript websites for inspiration, but nothing I've tried so far has worked. I appreciate any help anyone can provide! (If you need me to post any other code, please advise and I'll be happy to oblige.)

Editing Content of a Text Layer in Photoshop Using Javascript

I am trying to write a script to edit the content of a Text Layer in Photoshop CS6. Is that possible?
I have about 2000 images that I need to process for a work project. First I am adding the filename of each image as a text layer in Photoshop using a javascript I already have (see below). A sample filename is "UCMC_0018015 D FSH E." My script successfully adds this filename to the image as a text layer in Photoshop.
However, I would then like to edit the text layer in order to replace the underscore with a space, and removing " FSH E" from the end of the text string (all file names have these elements, but the numbers in the file name varies from file to file). Can anyone help me with the script I need to do this? I am new to writing and running scripts, but I am doing my best to learn on the job. Any advice you can give me would be appreciated.
Here is my current script for adding the filename to the image. I am not sure if I can edit it or if I will need to write a new script to edit the text layer. Thank you for your help!
//Check if a document is open
if ( documents.length > 0 )
{
var originalRulerUnits = preferences.rulerUnits;
preferences.rulerUnits = Units.PERCENT;
try
{
var docRef = activeDocument;
// Create a text layer at the front
var myLayerRef = docRef.artLayers.add();
myLayerRef.kind = LayerKind.TEXT;
myLayerRef.name = "Filename";
var myTextRef = myLayerRef.textItem;
//Set your parameters below this line
//If you wish to show the file extension, change the n to y in the line below, if not use n.
var ShowExtension = "n";
// Insert any text to appear before the filename, such as your name and copyright info between the quotes.
//If you do not want extra text, delete between the quotes (but leave the quotes in).
var TextBefore = "";
// Insert any text to appear after the filename between the quotes.
//If you do not want extra text, delete between the quotes (but leave the quotes in).
var TextAfter = "";
// Set font size in Points
myTextRef.size = 30;
//Set font - use GetFontName.js to get exact name
myTextRef.font = "Times New Roman";
//Set text colour in RGB values
var newColor = new SolidColor();
newColor.rgb.red = 0;
newColor.rgb.green = 0;
newColor.rgb.blue = 0;
myTextRef.color = newColor;
// Set the position of the text - percentages from left first, then from top.
myTextRef.position = new Array( 75, 98);
// Set the Blend Mode of the Text Layer. The name must be in CAPITALS - ie change NORMAL to DIFFERENCE.
myLayerRef.blendMode = BlendMode.NORMAL;
// select opacity in percentage
myLayerRef.opacity = 100;
// The following code strips the extension and writes tha text layer. fname = file name only
di=(docRef.name).indexOf(".");
fname = (docRef.name).substr(0, di);
//use extension if set
if ( ShowExtension == "y" )
{
fname = docRef.name
}
myTextRef.contents = TextBefore + " " + fname + " " + TextAfter;
}
catch( e )
{
// An error occurred. Restore ruler units, then propagate the error back
// to the user
preferences.rulerUnits = originalRulerUnits;
throw e;
}
// Everything went Ok. Restore ruler units
preferences.rulerUnits = originalRulerUnits;
}
else
{
alert( "You must have a document open to add the filename!" );
}
You can use a regular expression to remove all the whitespace and replace them with underscores. As far as I understand you can do a literal replace for " FSH E" to an empty string first. If those letters are different then you'll have to use a different tactic. But this will work for now. This is the basic part of the code that you need.
var myFileName = "UCMC_0018015 D FSH E";
// remove " FSH E"
myFileName = myFileName.replace(" FSH E", "");
// replace whitespce with underscores
myFileName = myFileName.replace(/\s/gi, "_");
alert(myFileName);
Your final code should look like this
//Check if a document is open
if ( documents.length > 0 )
{
var originalRulerUnits = preferences.rulerUnits;
preferences.rulerUnits = Units.PERCENT;
try
{
var docRef = activeDocument;
// Create a text layer at the front
var myLayerRef = docRef.artLayers.add();
myLayerRef.kind = LayerKind.TEXT;
myLayerRef.name = "Filename";
var myTextRef = myLayerRef.textItem;
//Set your parameters below this line
//If you wish to show the file extension, change the n to y in the line below, if not use n.
var ShowExtension = false;
// Insert any text to appear before the filename, such as your name and copyright info between the quotes.
//If you do not want extra text, delete between the quotes (but leave the quotes in).
var TextBefore = "";
// Insert any text to appear after the filename between the quotes.
//If you do not want extra text, delete between the quotes (but leave the quotes in).
var TextAfter = "";
// Set font size in Points
myTextRef.size = 30;
//Set font - use GetFontName.js to get exact name
myTextRef.font = "Times New Roman";
//Set text colour in RGB values
var newColor = new SolidColor();
newColor.rgb.red = 0;
newColor.rgb.green = 0;
newColor.rgb.blue = 0;
myTextRef.color = newColor;
// Set the position of the text - percentages from left first, then from top.
myTextRef.position = new Array( 75, 98);
// Set the Blend Mode of the Text Layer. The name must be in CAPITALS - ie change NORMAL to DIFFERENCE.
myLayerRef.blendMode = BlendMode.NORMAL;
// select opacity in percentage
myLayerRef.opacity = 100;
// The following code strips the extension and writes tha text layer. fname = file name only
var fname = docRef.name;
// code changes here.
// remove " FSH E"
fname = fname.replace(" FSH E", "");
// replace whitespaces with underscores
fname = fname.replace(/\s/gi, "_");
//use extension if set
if ( ShowExtension == true )
{
di =(fname).lastIndexOf(".");
fname = (fname).substr(0, di);
}
myTextRef.contents = TextBefore + " " + fname + " " + TextAfter;
}
catch( e )
{
// An error occurred. Restore ruler units, then propagate the error back
// to the user
preferences.rulerUnits = originalRulerUnits;
throw e;
}
// Everything went Ok. Restore ruler units
preferences.rulerUnits = originalRulerUnits;
}
else
{
alert( "You must have a document open to add the filename!" );
}
As your new to JavasScript, I'd like to point out that you have the showextension variable as a string. It's probably easier for it to be a Boolean. So it can only ever be TRUE or FALSE. A string could be, well... anything.
Another point is you had indexOf to find the extension. which will work fine. Unless you have a filename such as "my.lovely.photo.jpg"; whereas your extension would be "lovely.photo.jpg" Using lastIndexOf, as you might guess, finds the index of the item near the end of the string.

Is it possible to highlight all words on a web page without destroying the layout?

I've written an extension for firefox which highlights all words on a web page (excluding some words in a given list).
What i've noticed is that (besides that my extension is terribly slow) some web pages get "destroyed", more specifically the layout gets destroyed (particularly websites with overlay advertising or fancy drop-down menus).
My code wraps <span> tags around every "word", or to be precise around every token, because i'm splitting the text nodes with a whitespace as seperator.
So is it possible anyway to realize this task without destroying the page's layout?
I'm iterating over all text nodes, split them, and iterate over every token.
When the token is in my list, i don't highlight it, else i wrap the <span> tag around it.
So any suggestions how this could be done faster would be helpful, too.
Here are some screenshots for a correctly highlighted and a not correctly highlighted web page:
right:
en.wikipedia.org before highlighting,
en.wikipedia.org after highlighting.
wrong:
developer.mozilla.org before highlighting,
developer.mozilla.org after highlighting.
OK. Study this code. It searches for all instances of "is" and highlights if it is not surrounded by word characters. Put this in your scratchpad while this tab is focused. You will see that words like "List" and other words containing "Is" are no highlighted, but all the "Is"'s are.
I basically made an addon here for you. You can now release this as an addon called RegEx FindBar and take all the credit....
var doc = gBrowser.contentDocument;
var ctrler = _getSelectionController(doc.defaultView);
var searchRange = doc.createRange();
searchRange.selectNodeContents(doc.documentElement);
let startPt = searchRange.cloneRange();
startPt.collapse(true);
let endPt = searchRange.cloneRange();
endPt.collapse(false);
let retRane = null;
let finder = Cc["#mozilla.org/embedcomp/rangefind;1"].createInstance().QueryInterface(Ci.nsIFind);
finder.caseSensitive = false;
var i = 0;
while (retRange = finder.Find('is', searchRange, startPt, endPt)) {
i++;
var stCont = retRange.startContainer;
var endCont = retRange.endContainer;
console.log('retRange(' + i + ') = ', retRange);
console.log('var txt = retRange.commonAncestorContainer.data',retRange.commonAncestorContainer.data);
//now test if one posiion before startOffset and one position after endOffset are WORD characters
var isOneCharBeforeStCharWordChar; //var that holds if the character before the start character is a word character
if (retRange.startOffset == 0) {
//no characters befor this characte so obviously not a word char
isOneCharBeforeStCharWordChar = false;
} else {
var oneCharBeforeStChar = stCont.data.substr(retRange.startOffset-1,1);
if (/\w/.test(oneCharBeforeStChar)) {
isOneCharBeforeStCharWordChar = true;
} else {
isOneCharBeforeStCharWordChar = false;
}
console.log('oneCharBeforeStChar',oneCharBeforeStChar);
}
var isOneCharAfterEndCharWordChar; //var that holds if the character before the start character is a word character
if (retRange.endOffset == endCont.length - 1) {
//no characters after this characte so obviously not a word char
isOneCharAfterEndCharWordChar = false;
} else {
var oneCharAferEndChar = endCont.data.substr(retRange.endOffset,1); //no need to subtract 1 from endOffset, it takes into account substr 2nd arg is length and is treated like length I THINK
if (/\w/.test(oneCharAferEndChar)) {
isOneCharAfterEndCharWordChar = true;
} else {
isOneCharAfterEndCharWordChar = false;
}
console.log('oneCharAferEndChar',oneCharAferEndChar);
}
if (isOneCharBeforeStCharWordChar == false && isOneCharAfterEndCharWordChar == false) {
//highlight it as surrounding characters are no word characters
_highlightRange(retRange, ctrler);
console.log('highlighted it as it was not surrounded by word charactes');
} else {
console.log('NOT hilte it as it was not surrounded by word charactes');
}
//break;
startPt = retRange.cloneRange();
startPt.collapse(false);
}
/*********************/
function _getEditableNode(aNode) {
while (aNode) {
if (aNode instanceof Ci.nsIDOMNSEditableElement)
return aNode.editor ? aNode : null;
aNode = aNode.parentNode;
}
return null;
}
function _highlightRange(aRange, aController) {
let node = aRange.startContainer;
let controller = aController;
let editableNode = this._getEditableNode(node);
if (editableNode)
controller = editableNode.editor.selectionController;
let findSelection = controller.getSelection(Ci.nsISelectionController.SELECTION_FIND);
findSelection.addRange(aRange);
if (editableNode) {
// Highlighting added, so cache this editor, and hook up listeners
// to ensure we deal properly with edits within the highlighting
if (!this._editors) {
this._editors = [];
this._stateListeners = [];
}
let existingIndex = this._editors.indexOf(editableNode.editor);
if (existingIndex == -1) {
let x = this._editors.length;
this._editors[x] = editableNode.editor;
this._stateListeners[x] = this._createStateListener();
this._editors[x].addEditActionListener(this);
this._editors[x].addDocumentStateListener(this._stateListeners[x]);
}
}
}
function _getSelectionController(aWindow) {
// display: none iframes don't have a selection controller, see bug 493658
if (!aWindow.innerWidth || !aWindow.innerHeight)
return null;
// Yuck. See bug 138068.
let docShell = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShell);
let controller = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsISelectionDisplay)
.QueryInterface(Ci.nsISelectionController);
return controller;
}
Oh edit my solution out, will update with proper solution, I see you want to highlight all words
This is the code how firefox highlights stuff without changing document: Finder.jsm - _highlight function. You will have to copy this and use it for the whole document, if you need help let me know and I'll do it.
Here was my solution to highlight all matches of single word: https://stackoverflow.com/a/22206366/1828637
Here man this is how you are going to highlight the whole document, I didn't finish the snippet but this is the start of it: Gist - HighlightTextInDocument
Here's the copy paste answer to highlight everything in the document. As you learn more about it share with us, like how you can highlight with a different color, right now its all pink O_O
function _getEditableNode(aNode) {
while (aNode) {
if (aNode instanceof Ci.nsIDOMNSEditableElement)
return aNode.editor ? aNode : null;
aNode = aNode.parentNode;
}
return null;
}
function _highlightRange(aRange, aController) {
let node = aRange.startContainer;
let controller = aController;
let editableNode = this._getEditableNode(node);
if (editableNode)
controller = editableNode.editor.selectionController;
let findSelection = controller.getSelection(Ci.nsISelectionController.SELECTION_FIND);
findSelection.addRange(aRange);
if (editableNode) {
// Highlighting added, so cache this editor, and hook up listeners
// to ensure we deal properly with edits within the highlighting
if (!this._editors) {
this._editors = [];
this._stateListeners = [];
}
let existingIndex = this._editors.indexOf(editableNode.editor);
if (existingIndex == -1) {
let x = this._editors.length;
this._editors[x] = editableNode.editor;
this._stateListeners[x] = this._createStateListener();
this._editors[x].addEditActionListener(this);
this._editors[x].addDocumentStateListener(this._stateListeners[x]);
}
}
}
function _getSelectionController(aWindow) {
// display: none iframes don't have a selection controller, see bug 493658
if (!aWindow.innerWidth || !aWindow.innerHeight)
return null;
// Yuck. See bug 138068.
let docShell = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShell);
let controller = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsISelectionDisplay)
.QueryInterface(Ci.nsISelectionController);
return controller;
}
var doc = gBrowser.contentDocument;
var searchRange = doc.createRange();
searchRange.selectNodeContents(doc.documentElement);
_highlightRange(searchRange,_getSelectionController(gBrowser.contentWindow))
#jervis, I can't make a comment on your comment under #Noitidart code as I don't have 50rep yet. So I have to post here.
Re:
I did it with 'gFindBar._highlightDoc(true, word)' now. I'm using firefox 17, so i dont know if gFindBar is state of the art. – jervis 40 mins ago
But I tested his code and and it works.
Don't use gFindBar.
Copy it and then paste it into your Scratchpad.
Why are you using gFindBar._highlightDoc(true, word) ? I thoght you wanted to highlight everything in the document? Where did you get _highlightDoc from? I don't see that anywhere in #Noitidart's code.
Regading yoru comment on iterate all words and use gFindBar._highlightDoc:
I did it with 'gFindBar._highlightDoc(true, word)' now. I'm using firefox 17, so i dont know if gFindBar is state of the art. – jervis 39 mins ago
Dude why do that.... I saw #Noitidart posted a per word solution on the linked topic: gBrowser.tabContainer.childNodes[0].linkedBrowser.finder.highlight(true, 'YOUR_WORD_HERE'); that is extremely easy, one line and no need to create text nodes spans or anything. You have to run this code on each tab you want to highlight in.

Accept the input and check the mask in the reverse way

I need to develop an javascript function to check the mask reversely.
It means,
if I set the mask "###:##",
When I type "1" it shows, "1" When I
type "2" it shows, "21"
When I type "3"
it shows ,"3:21"
etc..
Is it possible to develop like that??
I have no idea how to start it? Can anyone put me on the right direction?
Update:
What the OP wants is a way to pass a custom mask to an input and have it auto-mask on every keypress - my original answer was assuming a hardset mask.
This is not a final solution, but should get you started if you don't want to use a plugin:
Jsfiddle (does not do what OP requests exactly at the moment) - but gets close.
var masker = {
mask : '', // custom mask that will be defined by user
types : {
'#' : '[\\d]', // number
'z': '[\\w]', // alpha
'*': '[\\d\\w]' // number or alpha
},
maskMatch : '', // regex used for matching
maskReplace : '', // replace string
makeTemplate : function(){
// basically we want to take the custom mask
// and make it into a regex match with capture groups
// and a replace string with the added separator(s)
// first we need to split the mask into like groups:
// ex: ###:## -> [#,#,#][:][#,#]
// so we get the indexes to slice it up later
var m = masker.mask.split('');
var len = m.length-1;
var indexes=[];
for (var i=0;i<len;i++){
if(m[i]!=m[i+1]){
indexes.push(i);
}
}
// now we slice it into groups
var groups = [];
for(var i=0;i<=indexes.length;i++){
var start = (i==0) ? 0 : indexes[i-1]+1;
var end = (i==indexes.length) ? m.length : indexes[i]+1;
groups.push(m.slice(start,end));
}
console.log(groups);
var reg = '';
var groupCount=1; // replace starts with $1
var replace = '';
// loop through to see if its using a wildcard
// replace with the wildcard and the number to match
// this will need to be reworked since it assumes
// {1,n} -- can't change the 1 at this moment
for(var i=0;i<groups.length;i++){
var l = groups[i][0];
if(l!='#'&&l!='z'&&l!='*'){
replace+= groups[i].join('');
continue;
}
replace+='$'+groupCount;
groupCount++;
reg+='(';
reg+=masker.types[l];
if(groups[i].length>1){
reg+='{1,';
reg+= groups[i].length;
reg+='}';
}
reg+=')';
}
console.log(reg);
console.log(replace);
masker.maskReplace = replace;
masker.maskMatch = new RegExp(reg);
},
matchIt: function(text)
{
// only replace if is match
if(text.match(masker.maskMatch)){
text = text.replace(masker.maskMatch,masker.maskReplace);
}
return text;
},
setup: function(id){
// you need a way to store the actual numbers (non-masked version)
// this is quick way, but should be incorporated as a variable
var hiddenText = $(id).clone().css({'left':'-9999px','position':'absolute'}).prop('id',id.substring(1,id.length)+'hidden').appendTo($(id));
$('#maskme').bind('keyup',function(e){
// fix this to better handle numpad, etc
var c = String.fromCharCode(e.which);
if(c.match(/[\w\d]/)){
$(id+'hidden').val( $(id+'hidden').val()+c);
$(id).val(masker.matchIt($(id+'hidden').val()));
} else {
// need a way to tell if user has highlighted then backspace
// or highlight and space... basically something for highlighting
if(e.which==8){ // 8 is backspace
// update our hidden value / stored value with what the user wants
var old = $(id+'hidden').val();
$(id+'hidden').val( old.substring(0,old.length-1));
}
}
});
}
}
Then calling it:
masker.mask = '###:##';
masker.makeTemplate();
masker.setup('#maskme');
If you want something more advanced take a look at the jQuery Masked Input project over a github. It already has handlers for all the different keypresses and other events, a more flexible custom matching, and many other things that should be thought about.

Categories