Javascript change name format from AD container - javascript

I'm trying to change the format of how a name displays when a distinguished name is in the format "CN=Doe\, John" to display as "John Doe". How can I change this code to account for it?
function changeName(name) {
if (name.startsWith("CN=")) {
if (name.indexOf("CN=", 3) != -1) {
name = name.substring(3, name.indexOf('CN=', 3) - 1);
} else if (name.indexOf("OU=", 3) != -1) {
name = name.substring(3, name.indexOf('OU=', 3) - 1);
}
} else if (name.startsWith("(null)")) {
name = "";
}
return name;
}
console.log(changeName('CN=Doe, John'));

Just like that. This assumes that names are always split with comma + space and there's equal sign.
function changeName(name) {
if (name.startsWith("CN=") || name.startsWith("OU=")) {
const parts1 = name.split(', ');
const parts2 = parts1[0].split('=');
return `${parts1[1]} ${parts2[1]}`;
} else if (name.startsWith("(null)")) {
return '';
}
return null;
}
console.log(changeName('CN=Doe\, John'));
Reference: split

Related

Javascript How to check the length of multiple variables and return the result in an efficient way?

At the moment I have an if the condition that checks if any of the string variable lengths is greater than 2 if true check for another condition, else console.log the output.
var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
// check for changes
if (
previous_data_change.length >= 2 ||
current_data_start.length >= 2 ||
current_data_end.length >= 2 ||
current_data_profile.length >= 2
) {
if (previous_data_change.includes("last_changed")) {
console.log(`last change comments: ${previous_data_change}`)
}
} else {
console.log(`no change in previous record`)
}
i have tried refactoring it using some,
var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
var filter_col = [
previous_data_change,
current_data_change,
current_data_end,
current_data_profile
];
change_boolean = filter_col.some((element) => element.length >= 2);
if (change_boolean && previous_data_change.includes("last_changed")) {
console.log(`last change comments: ${previous_data_change}`);
} else {
console.log("no change in previous record");
}
is there any way to shorten it further?
Since you want any of them to be length greater than 2. You can simply merge them instead of writing 4 if conditions.
var previous_data_change = 'last_changed on 10/01/2019 13:56:34';
var current_data_change= "";
var current_data_end = "";
var current_data_profile = "normal";
var string_to_check = previous_data_change + current_data_start + current_data_end + current_data_profile;
// check for changes
if (string_to_check.length < 2) {
console.log(`no change in previous record`)
return false;
}
if (previous_data_change.includes("last_changed")) {
console.log(`last change comments: ${previous_data_change}`)
return true;
}

Make a change to Javascript code that renumbers a list

I am unfamiliar with Javascript, but I would like to make a change to the following code. Currently, it renames macros in the program Keyboard Maestro in the format of 01), 02), etc. I would like it to simply use the format of a number followed by a space instead (i.e. 1 , 2 , etc.) I hope what I described makes sense. Thanks!
Part 1:
(function(inDesignMode) {
'use strict';
function dump(obj, desc) {
console.log((desc ? desc + ": " : "") + JSON.stringify(obj, null, "\t"));
}
var KMEditor = (function() {
var _editorAppName = "Keyboard Maestro";
var _editorApp;
return {
getEditorApp: function() {
return _editorApp ? _editorApp : _editorApp = Application(_editorAppName);
},
getEditorAppName: function() {return _editorAppName;},
getSelectedMacrosOrGroups: function() {
return this.getEditorApp().selectedmacros();
}
};
})();
var KMEngine = (function() {
var _engineApp;
return {
getAllMacrosSourceFileName: function() {
return this.getAppSupportFolderName() + "Keyboard Maestro Macros.plist";
},
getAppSupportFolderName: function() {
var app = Application.currentApplication();
app.includeStandardAdditions = true;
return app.pathTo('application support', { from: 'user domain' }) +
"/Keyboard Maestro/";
},
getEngineAppName: function() {
return "Keyboard Maestro Engine";
},
getEngineApp: function() {
if (!_engineApp)
_engineApp = Application(this.getEngineAppName());
return _engineApp;
},
readPlistBinaryFile: function(path) {
var data = $.NSData.dataWithContentsOfFile(path);
return ObjC.deepUnwrap(
$.NSPropertyListSerialization.propertyListWithDataOptionsFormatError(
data, $.NSPropertyListBinaryFormat_v1_0, 0, null));
},
};
})();
function getMacrosInfo(selectedMacroUUIDs) {
function getMacroName(macro) {
if (macro.Name)
return macro.Name;
throw Error("Un-named Macro UUID: " + macro.UID);
}
function getMacroInfo(macro) {
var info = {
macroUUID: macro.UID,
macroName: getMacroName(macro)
};
var matches = info.macroName.match(/^(\d\d)?(\))?(.*)/);
if (!matches || matches.length != 4)
throw Error("Could not parse macro name '" + info.macroName + "'");
info.prefixNumber = matches[1] || "";
info.macroNameNoPrefix = matches[3].trim();
return info;
}
function reOrderResult(macrosInfo, selectedMacroUUIDs) {
macrosInfo.macros = selectedMacroUUIDs.map(function(selectedMacroUUID) {
var info = macrosInfo.macros.find(function(macroInfo) {
return macroInfo.macroUUID === selectedMacroUUID;
});
if (!info)
throw Error("Could not find macro information for UUID '" + selectedMacroUUID + "'");
return info;
});
}
// getMacrosInfo()
var result = {
macros: []
};
var macroGroup;
var plist = KMEngine.readPlistBinaryFile(KMEngine.getAllMacrosSourceFileName());
plist.MacroGroups.forEach(function(group) {
if (group.Macros) {
group.Macros.forEach(function(macro) {
if (selectedMacroUUIDs.indexOf(macro.UID) >= 0) {
if (!result.groupUUID) {
macroGroup = group;
result.groupUUID = group.UID;
result.groupName = group.Name;
result.groupToggleMacroUID = group.ToggleMacroUID;
} else if (result.groupUUID !== group.UID) {
throw Error("Selected macros must all be from the same group");
}
result.macros.push(getMacroInfo(macro));
}
});
}
});
reOrderResult(result, selectedMacroUUIDs);
return result;
} // getMacrosInfo()
function execute() {
var selectedMacroUUIDs = KMEditor.getSelectedMacrosOrGroups();
if (!selectedMacroUUIDs || selectedMacroUUIDs.length < 2)
throw Error("You must select two or more macros");
var result = getMacrosInfo(selectedMacroUUIDs);
return JSON.stringify(result);
}
if (inDesignMode) {
return execute();
} else {
try {
return execute();
} catch (e) {
return "Error: " + e.message;
}
}
})(false);
Part 2:
(function(inDesignMode, designModeParams) {
'use strict';
var _kme = Application("Keyboard Maestro Engine");
function getKMVariable(name, required) {
var result = undefined;
if (inDesignMode && designModeParams)
result = designModeParams[name];
if (result === undefined)
result = _kme.getvariable(name);
if (required && !result)
throw Error("Variable '" + name + "' is empty");
return result;
}
var _km = Application("Keyboard Maestro");
function execute() {
var macroId = getKMVariable("palorg_MacroUUID", true);
var newName = getKMVariable("palorg_NewMacroName", true);
var macros = _km.macros.whose({id: {"=": macroId}});
if (macros.length == 0)
throw new Error("Macro '" + macroId + "' not found");
var macro = macros[0];
macro.name = newName;
return "OK";
}
if (inDesignMode) {
try {
return execute();
} catch (e) {
return "Error on line: " + e.line + ": " + e.message;
} finally {
try {
Application("Atom").activate();
} catch (e) {
}
}
} else {
try {
return execute();
} catch (e) {
return "Error: " + e.message;
}
}
})(false);
As per clarifications obtained in your comment, this is what you need:
01)macro --> 1 macro
To get that, you can try adding the following lines in execute() function in Part 2:
const regExp = /^0(.)\)/i; //Creates the regular expression
newName.replace(regex, '$1 '); //Replaces the match from the regex with a substring
macro.name = newName;
This is a regular expression substring replacement (more details here). Here's the breakdown on what's being done.
The ^ symbol denotes that a substring is being searched from the beginning of the string.
The next 0 is just a literal search for a 0 at the beginning of the string.
The next ( starts a parenthesized submatch string whose utility will be explained later.
The . indicates any single character.
The next ) end the parenthesized submatch string started earlier.
The next \) is for searching a ) literally which needs to be escaped with \ since ) has a special meaning of ending a parenthesized submatch string as mentioned above.
Now, the parenthesized submatch string is used so that after matching against the regular expression, the result can be used further to replace the matched string with. In this case,
01)macro will match 1 as the parenthesized submatch string since that's a single character after the leading 0 and before the ). This is used as $1 in the replace function so that after matching 01), it's replaced with 1 (notice the extra space, as is required by the question).

How can I uppercase names with a dash -, apostrophe ' or space?

I have the following code which works well to convert data entered into the "Firstname" field in our data enrollment software application to uppercase and return the converted value back to the application.
However, it doesn't handle names with "-", "'" or spaces in them, for example Anne-Marie, Jean Jacques, O’Brian. Could someone please help me in adding a few lines of code to handle these name types as well as preserving my original code which works for standard names without these characters in? Here is my code.
var tc_event = changeValue();
function changeValue() {
// Parse the JSON string for script information.
var tcInfo = JSON.parse(TC_Info);
/* FROM ENGINEERING: The “TC_Info” variable contains the user id and IP address of the user running the script.
* We have at least one customer that wanted that information */
var userId = tcInfo.userId;
var ipAddress = tcInfo.ipAddress;
// Parse the JSON string for fields and properties.
var tcData = JSON.parse(TC_Event);
// The following several lines of code loops over the workflow fields passed in to the script and saves references to the fields named “Lastname” and “LastnameUppercase”
var Lastname, LastnameUppercase, Firstname, Firstname1stUppercase;
// Iterate through parsed JSON.
for (var index in tcData) {
// Fetch each field i.e each key/value pair.
var field = tcData[index];
// Find the fields to process.
if (field.name === 'Lastname') {
Lastname = field;
} else if (field.name === 'LastnameUppercase') {
LastnameUppercase = field;
} else if (field.name === 'Firstname') {
Firstname = field;
} else if (field.name === 'Firstname1stUppercase') {
Firstname1stUppercase = field;
} else if (field.name === 'PersNr') {
PersNr = field;
} else if (field.name === 'TikNr') {
TikNr = field;
}
}
// Were the fields found? If so, proceed.
if (Lastname && LastnameUppercase && Firstname && Firstname1stUppercase && PersNr && TikNr) {
// This line of code states the LastnameUppercase field value will be the Lastname field value in uppercase
LastnameUppercase.value = Lastname.value.toUpperCase();
Firstname1stUppercase.value = Firstname.value.charAt(0).toUpperCase() + Firstname.value.slice(1);
var strLtr = PersNr.value.substring(0, 2);
var strNum = PersNr.value.substring(2, 6);
if (strLtr === '00') {
strLtr = 'A';
} else if (strLtr === '01') {
strLtr = 'M';
} else if (strLtr === '31') {
strLtr = 'B';
} else if (strLtr === '71') {
strLtr = 'F';
}
TikNr.value = strLtr + strNum;
}
// Return the updated fields and properties.
return JSON.stringify(tcData);
}
This will capitalize both the firstName that do not contain symbols and the ones that do:
function capitalize(name) {
let capitalizedName = '';
const nameSplit = name.split(/\W/g);
const symbols = name.match(/\W/g);
for(let i = 0; i< nameSplit.length; i++) {
capitalizedName += nameSplit[i][0].toUpperCase() +
nameSplit[i].slice(1)
if(i < nameSplit.length -1) capitalizedName += symbols[i];
}
return capitalizedName
}
I have used this function successfully:
function capitalizeName(str) {
var result = str.replace(/\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
return result.replace(/\s\s+/g, ' ');
}
calling the function:
capitalName = capitalizeName(lowerCaseName)
Looks like you should change
Firstname1stUppercase.value = Firstname.value.charAt(0).toUpperCase() + Firstname.value.slice(1);
to
var delimiter = ''; //char value
if(Firstname.value.indexOf(' ') != -1){ //name has a space
delimiter = ' ';
}else if(Firstname.value.indexOf('-') != -1){ //name has -
delimiter = '-';
}else if(Firstname.value.indexOf('\'') != -1){ //name has a '
delimiter = '\'';
}
Firstname1stUppercase.value = Firstname.split(delimeter).map(function(val) {
return val.charAt(0).toUpperCase() + val.slice(1);
}).join(delimeter);
The last line is what you were doing but written for any separating character be it a space, apostrophe, or hyphen.
You could split by non alphabetic letters, like this:
text.split(/[^A-Za-z]/);
inspired from here: Split string by non-alphabetic characters
Now, let's implement the function you need:
function myUpperCase(input) {
var parts = input.split(/[^A-Za-z]/);
var output = parts[0];
for (var i = 1; i < parts.length; i++) {
if (parts[i].length) parts[i] = parts[i][0].toUpperCase() + parts[i].substring(1);
output += input[output.length] + parts[i];
}
return output;
}

display the recursion line by line

I am trying to make a function in javascript that would expand/split a string with dashes and show the process ( line by line ) using recursion.
for example, the string "anna" would become:
expand("anna") = expand("an")+"---"+expand("na") ->
"a"+"---"+"n"+"---"+"n"+"---"+"a"
and the desired output would be:
anna
an---na
a---n---n---a
I have achieved doing the following so far (I know it might not be the solution I am looking):
expand("anna") = an+"---"+expand("na")
= an+"---"+n+"---"+expand("a");
= an+"---"+n+"---+"a"
the output I am getting is:
an---n---a
I can't seem to concatenate the head though to do the first example.
My javascript function of expand is as follows:
function expand(word) {
if (word.length<=1) {
return word;
} else {
mid = word.length/2;
return word.substr(0,mid) + " " + expand(word.substr(mid,word.length));
}
}
document.write(expand("anna"));
I would need some tips to do this, otherwise (if it's the wrong stackexchange forum), please guide me where to post it.
this is my crazy attempt
var Word = function(str) {
this.isSplitable = function() {
return str.length > 1;
}
this.split = function() {
var p = Math.floor(str.length / 2);
return [
new Word(str.substr(0,p)),
new Word(str.substr(p,p+1))
];
}
this.toString = function() {
return str;
}
}
var expand = function(words) {
var nwords = [];
var do_recur = false;
words.forEach(function(word){
if(word.isSplitable()) {
var splitted = word.split();
nwords.push(splitted[0]);
nwords.push(splitted[1]);
do_recur = true;
}else{
nwords.push(word);
}
});
var result = [];
nwords.forEach(function(word){
result.push( word.toString() );
});
var result = result.join("--") + "<br/>";
if(do_recur) {
return result + expand(nwords);
}else{
return "";
}
}
document.write( expand([new Word("anna")]) );
This is what you need
expand = function(word) {
return [].map.call(word, function(x) {return x+'---'}).join('')
};
The joy of functional programming.
And with added code to deal with last character:
function expand(word) {
return [].map.call(word, function(x, idx) {
if (idx < word.length - 1)
return x+'---';
else return x
}).join('')
}
As I said that it is impossible to display the "process" steps of recursion while using recursion, here is a workaround that will output your desired steps:
var levels = [];
function expand(word, level) {
if (typeof level === 'undefined') {
level = 0;
}
if (!levels[level]) {
levels[level] = [];
}
levels[level].push(word);
if (word.length <= 1) {
return word;
} else {
var mid = Math.ceil(word.length/2);
return expand(word.substr(0, mid), level+1) + '---' + expand(word.substr(mid), level+1);
}
}
expand('anna');
for (var i = 0; i < levels.length; i++) {
console.log(levels[i].join('---'));
}
to see all steps the best that I whold do is:
function expand(word) {
if (word.length<=1) {
return word;
} else {
var mid = word.length/2;
var str1 = word.substr(0,mid);
var str2 = word.substr(mid,word.length);
document.write(str1 + "---" + str2 + "<br></br>");
return expand(str1) + "---" + expand(str2);
}
}
document.write(expand("anna"));
You have to return the two parts of the string:
function expand(word) {
output="";
if (word.length<=1) {
output+=word;
return output;
} else
{
var mid = word.length/2;
output+=word.substr(0,mid)+"---"+word.substr(mid)+" \n";//this line will show the steps.
output+=expand(word.substr(0,mid))+"---"+expand(word.substr(mid,word.length-1))+" \n";
return output;
}
}
console.log(expand("anna"));
Edit:
I added the output var and in every loop I concatenate the new output to it.
It should do the trick.
Hope the problem is in your first part. According to your algorithm, you are splitting your string anna in to two parts,
an & na
so you need to expand both parts until the part length is less than or equal to one. so your required function is the below one.
function expand(word) {
if (word.length<=1) {
return word;
} else {
mid = word.length/2;
return expand(word.substr(0,mid)) + " --- " + expand(word.substr(mid,word.length));
}
}
document.write(expand("anna"));

how to convert word to number then add

I'm making a system that will use a calculator, however, at any given time the user must click on a word, and that word needs to have a value, for example 20. see the example of how mathematical formula works:
car = 20;
2 + (car + 1);
the result of this formula is 23
these words and values ​​comes from database
Anyone know how to do this in javascript?
the javascript code:
function addChar(input, character) {
if (input.value == null || input.value == "0"){
input.value = character;
}
else{
input.value += character;
}
}
function cos(form) {
form.display.value = Math.cos(form.display.value);
}
function sin(form) {
form.display.value = Math.sin(form.display.value);
}
function tan(form) {
form.display.value = Math.tan(form.display.value);
}
function sqrt(form) {
form.display.value = Math.sqrt(form.display.value);
}
function ln(form) {
form.display.value = Math.log(form.display.value);
}
function exp(form) {
form.display.value = Math.exp(form.display.value);
}
function sqrt(form) {
form.display.value = Math.sqrt(form.display.value);
}
function deleteChar(input) {
input.value = input.value.substring(0, input.value.length - 1)
}
function changeSign(input) {
if (input.value.substring(0, 1) == "-"){
input.value = input.value.substring(1, input.value.length);
}
else{
input.value = "-" + input.value
}
}
function compute(form) {
form.display.value = eval(form.display.value)
}
function square(form) {
form.display.value = eval(form.display.value) *
eval(form.display.value)
}
var data = {"car":20};
var formula = " 2 + (%car% + 1)";
for (var index in data){
formula = formula.replace(new RegExp("%"+index+"%","g"),data[index]);
}
alert(eval(formula));
use prefix and suffix for ignoring partial match word replacing error.
i used %

Categories

Resources