UltraEdit scripting using JavaScript and wildcards - javascript

I have a program using a combination of JavaScript and UltraEdit scripting. The program has an array of strings to search for in a file/tab. If found, it moves the corresponding lines to a new file/tab. When using exact match it works great.
However, my source values are not exact matches. The values in the file are ######-## where the values after the dash vary. I have the value up to the dash. I attempted to build the wildcard into the array values, and I've attempted to concatenate it to the .find function with no success. Any thoughts would be greatly appreciated.
Here is the code I'm executing as a script within UltraEdit. I've truncated the array from the 50 values it contained for the purpose of demonstration.
// Start at the beginning of the file
UltraEdit.activeDocument.top();
// Search string variable used for copying of lines
//DD011881 - Building an array of values
var delString = new Array()
delString[0] = "'99999999'";
delString[1] = "'169-*'";
delString[2] = "'5482-*'";
delString[3] = "'5998-*'";
delString[4] = "'36226-*'";
delString[5] = "'215021-*'";
// Array loop value
var x = 0;
var arrayLen = delString.length
// Start with nothing on the clipboard
UltraEdit.clearClipboard();
for (x=0; x<arrayLen; x++)
{
// Establish our search string for the loop condition
var bFound = false;
while (UltraEdit.activeDocument.findReplace.find(delString[x])){
UltraEdit.activeDocument.selectLine();
UltraEdit.activeDocument.copyAppend("^c" + "\n");
bFound = true;
}
UltraEdit.activeDocument.top();
if (bFound) {
UltraEdit.document[6].paste();
UltraEdit.activeDocument.top();
UltraEdit.clearClipboard();
}
} // For Loop

In your UltraEdit script you want to run an UltraEdit regular expression find in the while loop, but you have never set the regular expression engine nor any find parameter. So the script is executing the find with the internal defaults for finds (case-insensitive, non-regular expression search downwards, not matching whole words with the Perl regular expression engine selected).
Insert in your UltraEdit script below the command UltraEdit.clearClipboard(); the following lines:
UltraEdit.ueReOn();
UltraEdit.activeDocument.findReplace.mode = 0;
UltraEdit.activeDocument.findReplace.matchCase = true;
UltraEdit.activeDocument.findReplace.matchWord = false;
UltraEdit.activeDocument.findReplace.regExp = true;
UltraEdit.activeDocument.findReplace.searchDown = true;
if (typeof(UltraEdit.activeDocument.findReplace.searchInColumn) == "boolean") {
UltraEdit.activeDocument.findReplace.searchInColumn = false;
}
Now the UltraEdit regular expression is selected for the script and the find parameters are set for running a case-sensitive (faster) regular expression search.
And please remove "^c" + "\n" from command UltraEdit.activeDocument.copyAppend() as this command does not take any parameter. With the command above, the entire line including the line termination is already selected and this selection is appended to the clipboard, not the string you put into the parentheses of command copyAppend().

Related

Javascript name field masking (Using regular expression)

i need to mask a name and i want it in Script.
i have a list format data.
Following is my jsp which put data in a variable.
<c:forEach value="${test}" var="v"/>
<c:set var = "nametest" value="${v.name}"
i only need names to be shown on the screen. so i made a variable only contains names. The problem is my script function doesn't look like
contain my data correctly.
Following is my script.
function maskingName(nametest){
var a = "${nametest}"
if (a === undefined || a ===''){
return '';
}
var pattern = /.$/;
return a.replace(pattern,"*");
}
after running it, i only get the last name (there are 10 names and it shows the only the last one)without masking.
My question is
1. how can i use List format in my script function?
2. why does the regular expression not working?
Thank you!
I have written a small java code that might help you understand better
static String maskingName(String nametest) {
if (nametest == null || nametest == "") {
return "";
}
String pStr = ".$" // ".*$";
Pattern pattern = Pattern.compile(pStr);
return pattern.matcher(nametest).replaceAll("***");
}
For input '12345' or '345345', the output will be '1234***' or '34534***'
Replacing pStr=".*$" will give output ******

How can I call this function only once yet loop as needed?

I have a Chrome extension that replaces certain phrases on webpages. It uses a 2 dimensional array. The [i][1] replaces the text in provided in the [i][0] value.
for (var i = 0; i < array.length; i++) {
findAndReplaceDOMText(document.body, {
preset: 'prose',
find: array[i][0],
replace: array[i][1]
});
}
This code works fine yet it seems computationally expensive as it calls the findAndReplaceDOMText function multiple times rather than just once. Is it possible to move the for loop inside the function to just wrap the find and replace params? If so what would that look like? I can only get console errors trying this.
Edit: The function traverses the DOM looking for all visible human readable text that contains the regex phrase provided at find and replaces with the string provided at replace.
Without modifying the function's behaviour, you can't. What you could do is separating the find and replace passes.
Your strings are stored in a kind of difficult to transverse way, so let's flat them out:
var flatFind = array.map(function(elem){
return elem[0]
})
var flatReplace = array.map(function(elem){
return elem[1]
})
Then, you'd need to create a regex string that encompasses all your search strings:
var searchString = "/("+flatFind.join("|")+")/g"
Then pass it to the function, using a function to find the index of the match:
findAndReplaceDOMText(document.body, {
preset: 'prose',
find: searchString,
replace: function(portion, match){
var idx = flatFind.indexOf(match)
if(idx > -1) return flatReplace[idx]
else throw "hey, there's no replacement string for this!"
}
})
You could try to use the replace parameter as a function.
The find-configuration-property then needs to be a regular expression (RegExp-object) constructed of your search strings (like /first|second|third/g). Do not forget the g-modifier at the end.
As replace-configuration-property you then create a function that checks which string occurred (you get that as the second parameter to your function). According to the match you then return the corresponding value (for example if match is "first" then you return "1st". If match is "second" then you return "2nd" and so on).

JQuery each() function code is running even when there are no elements in the collection

I have the following code in my application. It is supposed to build a comma separated string from a JQuery collection. The collection is retrieved from some xml. I use JQuery each() to iterate. This is standard code that I use all the time. I declare and define the result variable (patientConditions) first and set it to blank. Within the function I add the found string to the result variable along with a comma. I am not bothered by the trailing comma this leaves if there are results. The problem is that with no results the second line within my each() is running - they probably both are. After the loop has completed (with no matching elements in the xml) the value of the result is ','. It should be blank. I think this is something to do with closures, or hoisting, but I am unable to figure out how its happening. I have hacked a solution to this scenario, but am more worried about the hole in my js knowledge :(
var patientConditions = '';
$xml.find('patient>prescription>conditions').each(function() {
var conditionName = $(this).find('condition>name');
patientConditions += conditionName.text() + ',';
});
From what I can understand there is a match for patient>prescription>conditions, but not for condition>name, in that case $(this).find('condition>name') will return a zero elemet set. then .text() on that set will return a empty string
$xml.find('patient>prescription>conditions').each(function() {
var conditionName = $(this).find('condition>name');
if(conditionName.length){
patientConditions += conditionName.text() + ',';
}
});
Whenever a jQuery object is used to find non existant nodes, in this case $(this).find('condition>name'). The jQuery object still exists, it just contains no association to a node. This will allow you to run all jQuery functions on this object despite it not having any reference. This is why conditionName.text() returns an empty string despite no node being present. The solution, check if the node exists before doing anything.
var patientConditions = '';
$xml.find('patient>prescription>conditions').each(function() {
var conditionName = $(this).find('condition>name');
if (conditionName.length > 0) {
patientConditions += conditionName.text() + ',';
} else {
// Do something if node doesnt exist
}
});

JS - Splitting a string and looping through results

In JS, I'm having trouble working out how to split a string coming from an AJAX call.
This is what I have so far:
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
feedUpdateResponse = xmlhttp.responseText;
/////...split script.../////
}
}
xmlhttp.open("GET","https://myDomain.com/myScript.aspx",true);
xmlhttp.send();
Where you have /////...split script...///// in my script above, I need to add a little function that splits the string returned from my AJAX call.
The string simply contains names of DIVs, like this:
feedUpdateResponse = "div1/div2/div3/div4"
I would like to first split the string by its slashes (/) and run a loop through the different values and do stuff to those elements on my page.
To give an idea of what I need to achieve, I have given this example which is a mix of ASP & JS - it's the only way I can possibly describe it (and show that I've had an attempt) :)
MyArray = Split(feedUpdateResponse,"/")
For Each X In MyArray
documentGetElementById('updateAvailable_'+x).style.visibility="visible";
Next
On my page I have an ASP script that produces jquery carousels, all contained by separate DIVs. The DIVs are named DIV1, DIV2 etc. Inside DIV1, for example, is a text element called updateAvailable_div1 which will alert the user "There are new photos available for this feed, please click the refresh button".
Could somebody please explain to me how I can change my example above to work in JS? Just need to split the string into an array and loop through the split values...
You can use .split() to split a string on a specified character with the results returned as an array. So then it's just a matter of looping through the array:
// given your existing variable
// feedUpdateResponse = "div1/div2/div3/div4" as set in the
// code in the question, add this:
var a = feedUpdateResponse.split("/"),
i;
for (i = 0; i < a.length; i++) {
document.getElementById("updateAvailable_" + a[i]).style.visibility
= "visible";
}
Get your array via string.split("/"). Iterate your array using your method of choice. I prefer Array.forEach():
feedUpdateResponse.split("/").forEach(function (item) {
document.getElementById(item).style.visibility = "visible";
});
See the compatibility notes for using .forEach() in older browsers.
As an alternative:
for(element of feedUpdateResponse.split("/")){
do_your_thing();
}
Using for..in will end up giving you the indices on the array (keys), while for..on will give you the elements of the array (values).
You can also do:
for ([index, element] of Object.entries(feedUpdateResponse.split("/"))) {
do_your_thing();
}
In the event that you need the index.
The disadvantage is it not being compatible with IE, but for personal projects or a quick automation script it usually does me plenty fine.
Try this code:
var a = feedUpdateResponse.split("/");
for (i in a) {
document.getElementById("updateAvailable_" + a[i]).style.visibility
= "visible";
}
var feedUpdateResponse = "div1/div2/div3/div4";
var feedUpdateSplit = feedUpdateResponse.split("/");
for (var x = 0; x < feedUpdateSplit.length; x++) {
document.getElementById("updateAvailable_" + feedUpdateSplit[x]).style.visibility = "visible";
}

javascript regex - remove a querystring variable if present

I need to rewrite a querysting using javascript.
First I check to see if the variable is present, if it is I want to replace it with a new search term. If it is not present then I just add the new variable
I'm able to get it to work with simple terms like hat, ufc hat
whitespaces are %20, so ufc hat is really ufc%20hat
I run into problem with terms like make-up, hat -baseball, coffee & tea, etc..
What is the proper regex for this?
Below is my code, which doesn't work.
var url = String(document.location).split('?');
querystring = url[1];
if(querystring.match(/gbn_keywords=/)!=null)
querystring=querystring.replace(/gbn_keywords=[a-zA-Z0-9%20.]+/,"gbn_keywords="+term);
else
querystring=querystring+"&gbn_keywords="+term;
No Regex needed. To get the query arguments, take everything after ?. Then, split the string by & to return each argument. Split again by = to get the arg name (right of =) and the value (left of =). Iterate through each argument, a rebuild the URL with each argument, excluding the one you don't want. You shouldn't run into problems here because ?, &, and - must be escaped if they are to be used in arguments. You also said you want to add the argument if it doesn't exist, so just set a variable to true, while you are iterating through each argument, if you find the argument. If you didn't append it to the end of the query string that you rebuilt.
location objects already have perfectly good properties like pathname, hostname etc. that give you the separate parts of a URL. Use the .search property instead of trying to hack the URL as a string (? may not only appear in that one place).
It's then a case of splitting on the & character (and maybe ; too if you want to be nice, as per HTML4 B2.2) and checking each parameter against the one you're looking for. For the general case this requires proper URL-decoding, as g%62n_keywords=... is a valid way of spelling the same parameter. On the way out naturally you will need to encode again, to stop & going on to the next parameter (as well as to include other invalid characters).
Here's a couple of utility functions you can use to cope with query string manipulation more easily. They convert between the ?... string as seen in location.search or link.search and a lookup Object mapping parameter names to arrays of values (since form-url-encoded queries can have multiple instances of the same parameter).
function queryToLookup(query) {
var lookup= {};
var params= query.slice(1).split(/[&;]/);
for (var i= 0; i<params.length; i++) {
var ix= params[i].indexOf('=');
if (ix!==-1) {
var name= decodeURIComponent(params[i].slice(0, ix));
var value= decodeURIComponent(params[i].slice(ix+1));
if (!(name in lookup))
lookup[name]= [];
lookup[name].push(value);
}
}
return lookup;
}
function lookupToQuery(lookup) {
var params= [];
for (var name in lookup)
for (var i= 0; i<lookup[name].length; i++)
params.push(encodeURIComponent(name)+'='+encodeURIComponent(lookup[name][i]));
return params.length===0? '' : '?'+params.join('&');
}
This makes the usage as simple as:
var lookup= queryToLookup(location.search);
lookup['gbn_keywords']= ['coffee & tea'];
var query= lookupToQuery(lookup);
& character is used to seperate key and value pairs in the querystring. So that you can match all the characters except for & by re-writing your code as follows:
querystring=querystring.replace(/gbn_keywords=[^&]+/,"gbn_keywords="+term);
[^&]+ matches one or more characters up to & or end of string. But if there may situations where the querystring data may look like ...?gbn_keywords= (no value) then a slight modification is needed to the above line:
querystring=querystring.replace(/gbn_keywords=[^&]*/,"gbn_keywords="+term);
Just change + to * so that the regex will match 0 or more characters. I think this is better.
Why don't you run a split on url[1] and than replace the value of the gbn_keywords in that new array?
And if you use a JavaScript Framework, there might be a handy function that does all that. In Prototype there is the function toQueryParams().

Categories

Resources