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

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;
}

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;
}

Javascript change name format from AD container

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

Checking if a string isn't a space in Javascript

So I have a program that counts the words in a document that is loaded into an iFrame, all of the newline characters are replaced by a space, then the string is split by spaces, I then want to add them to a map as the key and set their value to 1 if they're not in the map or not a space, this is where I'm having the problem because it's still counting each space in the string , I feel like I'm being really stupid and missing something obvious...
var innerDoc = document.getElementById("pageinframe");
var innerDocContent = innerDoc.contentDocument.body.innerHTML;
var split = strip(innerDocContent).replace(/(\r\n|\n|\r)/gm, " ").split(" ");
var obj = new Map();
for (var x = 0; x < split.length; x++) {
console.dir(typeof split[x]);
if(!obj.has(split[x]) && (split[x] != " ")) {
obj.set(split[x], 1);
}
else if (split[x] != " ") {
obj.set(split[x], obj.get(split[x])+1);
}
}
function strip(str) {
var tmp = document.createElement("DIV");
tmp.innerHTML = str;
return tmp.textContent || tmp.innerText || "";
}
There are something, icant understand. When you split(' '). the array not contains ' ', only words!!!, https://www.w3schools.com/jsref/jsref_split.asp. Son Why need to testif is white space. Then i think, it could be in:
.replace(/(\r\n|\n|\r)/gm, " ")
The split array contained "" not " " like I originally thought. Like I said I was missing something really obvious, just needed to see what was in the array.
var innerDoc = document.getElementById("pageinframe");
var innerDocContent = innerDoc.contentDocument.body.innerHTML;
var split = strip(innerDocContent).replace(/(\r\n|\n|\r)/gm, " ").split(" ");
var obj = new Map();
for (var x = 0; x < split.length; x++) {
// Removing NaN for string
if(split[x].charCodeAt(0))
{
if(!obj.has(split[x]) && (split[x] != " ")) {
obj.set(split[x], 1);
}
else if (split[x] != " ") {
obj.set(split[x], obj.get(split[x])+1);
}
}
}
function strip(str) {
var tmp = document.createElement("DIV");
tmp.innerHTML = str;
return tmp.textContent || tmp.innerText || "";
}
console.log(obj);

Get function parameters from a JS function which is a string

I am parsing a webpage and I obtain the following JS function as a string
"translate(737.4170532226562,136.14541625976562)"
I want to parse the string to obtain the two parameters of the function.
I can parse the string upto the '(' and ',' and ')' to get the arguments - I wanted to know if there is any other method to get the parameters from this string function.
You can use regex for this purpose. For example this one: /([\d\.]+),([\d\.]+)/
var str = "translate(737.4170532226562,136.14541625976562)";
var args = /([\d\.]+),([\d\.]+)/.exec(str)
var a1 = args[1], a2 = args[2];
document.write(['First argument: ', a1, '<br> Second argument: ', a2].join(''))
This may be overkill. But I was bored. So here is a function name parser. It gets the function name and the arguments.
var program = "translate(737.4170532226562,136.14541625976562)";
function Parser(s)
{
this.text = s;
this.length = s.length;
this.position = 0;
this.look = '0'
this.next();
}
Parser.prototype.isName = function() {
return this.look <= 'z' && this.look >= 'a' || this.look <= '9' && this.look >= '0' || this.look == '.'
}
Parser.prototype.next = function() {
this.look = this.text[this.position++];
}
Parser.prototype.getName = function() {
var name = "";
while(parser.isName()) {
name += parser.look;
parser.next();
}
return name;
}
var parser = new Parser(program);
var fname = parser.getName();
var args = [];
if(parser.look == '(') {
parser.next();
args.push(parser.getName());
while(parser.look == ',') {
parser.next();
args.push(parser.getName());
}
} else {
throw new Error("name must be followed by ()")
}
console.log(fname, args);

Modify javascript code to iterate through all variables in the form

I have the following code that worked fine till now as I decided to add more variables to the form. How can I make this function smart and itterate and pass all the variables in the form?
function getquerystring(strFormName) {
var form = document.forms[strFormName];
var word = form.clock_code.value;
qstr = 'clock_code=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
complete JS code # pastie
It looks like you're serializing a form to a querystring? If that's the case, then this is one place where a JavaScript library is really nice.
Each of these will serialize the first form on the page to a querystring.
// ExtJS
var str = Ext.lib.Ajax.serializeForm(Ext.select('form').elements[0]);
// jQuery
var str = $("form").serialize();
// MooTools
var str = $$('form').toQueryString();
// PrototypeJS
var str = $$('form')[0].serialize();
You can see some other methods and how they compare at http://jquery.malsup.com/form/comp/
Try this
function formToQueryString(form) {
var elements = form.elements;
var cgi = [];
for (var i = 0, n = elements.length; i < n; ++i) {
var el = elements[i];
if (!el.name) { continue; }
if (el.tagName === 'INPUT' && (el.type === 'checkbox' || el.type === 'radio')
&& !el.checked) {
continue;
}
cgi.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value));
}
return cgi.length ? '?' + cgi.join('&') : '';
}
The issue with your code is that you're only grabbing the clock_code element value, and ignoring the rest. Here's a replacement I wrote up:
function getquerystring(strFormName) {
var qstr = '', word = '';
var key = 0;
var form = document.forms[strFormName];
var fields = ['clock_code', 'message', 'type'];
for (var i = 0; i<fields.length; i++) {
key = fields[i];
word = form[key].value;
if (qstr && qstr.length > 0) {
qstr += '&';
}
qstr += encodeURIComponent(key) + '=' + encodeURIComponent(word);
}
return qstr;
}
Benjamin's approach is a bit more flexible; mine only queries those fields specifically named in the fields array
Assuming they are all simple fields, the following should work just fine (didn't test it, though - sorry if it doesn't "compile"):
function getquerystring(strFormName) {
var qstr = '';
var form = document.forms[strFormName];
var elements = form.elements;
var first = true;
for (elem in elements) {
var word = elem.value;
var name = elem.name;
if (first) {
first = false;
} else {
qstr = qstr + '&';
}
qstr = qstr + name + '=' + escape(word);
}
return qstr;
}
Adding info on supporting multiple Element types:
The question only mentioned text fields so I assumed the easier answer would suffice. Wrong!
Glad you're able to use JQuery (which rocks), but for completeness I'll just flesh this out with a bit of info on how to build your own "dynamic form handler".
First, you have to add checking on the class of elem, like so:
function isCheckbox(o){ return (o && o.constructor == Checkbox) }
and you have to then do something a little different depending on the type of object you are looking at.
For example:
for (var elem in elements) {
var value = '';
var name = elem.name;
if (isCheckbox(elem)) {
value = elem.checked ? 'true' : 'false';
} else if (isSingleSelect(elem)) {
var index = elem.selectedIndex;
if(selected_index > 0) {
value = elem.options[selected_index].value;
}
}
}
There may be situations where you have to turn values into something that is meaningful to your app, like in a multiple-select combo box. You could send one name=value pair for each value or roll them into a comma-seperated list or the like - it all depends on your app. But with this approach one can certainly build the "dynamic form handler" that fits their specific needs.
Check out this article for helpful stuff about how to process each form field type: http://www.javascript-coder.com/javascript-form/javascript-get-form.htm

Categories

Resources