how to convert word to number then add - javascript

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 %

Related

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

isset equivalent in javascript to find palindrome

I created a script in PHP to find a palindrome, but when I try to do the same in JavaScript, then it is not working as expected. It's not just a matter of checking if the string that is reversed matches, but any order of the string has to be checked as well.
In other words, "mom" should return as true, "mmo" should return as true, "omm" should return as true, etc..., which is what the PHP script does, but the JS script below doesn't even work for the first iteration for the string "mom"
The following is the PHP script:
<?php
function is_palindrom($str) {
$str_array = str_split($str);
$count = array();
foreach ($str_array as $key) {
if(isset($count[$key])) {
$count[$key]++;
} else {
$count[$key] = 1;
}
}
$odd_counter = 0;
foreach ($count as $key => $val) {
if(($val % 2) == 1) {
$odd_counter++;
}
}
return $odd_counter <= 1;
}
echo is_palindrom('mom') ? "true" : "false";
The following is what I have tried in JS:
var count = [];
var strArr = [];
var oddCounter = 0;
var foreach_1 = function(item, index) {
console.log("count[index]: " + count[index]);
if (typeof count[index] !== "undefined") {
count[index]++;
} else {
count[index] = 1;
}
};
var foreach_2 = function(item, index) {
console.log("item: " + item + " item % 2: " + eval(item % 2));
if (eval(item % 2) == 1) {
oddCounter++;
}
console.log("oddCounter: " + oddCounter);
return oddCounter <= 1;
};
var isPalindrom = function(str) {
strArr = str.split("");
console.log(strArr);
strArr.forEach(foreach_1);
console.log(count);
count.forEach(foreach_2);
};
I believe it is failing where I try to replicate isset in javascript, with the following code:
if (typeof count[index] !== "undefined") {
As a result, I have tried to write my own isset function, but still the same result, it is not working:
var isset = function(obj) {
if (typeof obj === "undefined" || obj === null) {
return false;
} else {
return true;
}
};
With the following function being called:
if (isset(count[index])) {
count[index]++;
} else {
count[index] = 1;
}
As usual, any help would be appreciated and thanks in advance
BTW, it's killing me that I cannot remember the word for several revisions or iterations of something - I know that it starts with "re"
My attempt:
let p1 = `No 'x' in Nixon.`
let p2 = `Was it a car or a cat I saw?`
let p3 = `A man, a plan, a canal, Panama!`
function is_palindrome (str) {
const normalize = str => str.replace(/[.,:;`'"!?\/#$%\^&\*{}=\-_~()\s]/g, '').toLowerCase()
const reverse = str => [...str].reverse().join('')
return normalize(str) === reverse(normalize(str))
? true
: false
}
console.log(is_palindrome(p1))
console.log(is_palindrome(p2))
console.log(is_palindrome(p3))
First, thank you for all the comments.
Second, I ran a var_dump on the count array in the PHP file and this was the result:
array (size=2)
'm' => int 2
'o' => int 1
Which lead me to understand that count in js has to be an object for this work and I would have to create indexes of the object, depending on the string entered.
One thing lead to another and a complete re-write, but it works, along with a spell checker - see link at the bottom for complete code:
var count = {};
var strArr = [];
var oddCounter = 0;
var objKeys = [];
var splitString;
var reverseArray;
var joinArray;
var url = "test-spelling.php";
var someRes = "";
var mForN = function(obj, strArr) {
for (var y = 0; y < strArr.length; y++) {
// console.log("obj[strArr[" + y + "]]: " + obj[strArr[y]]);
if (isset(obj[strArr[y]])) {
obj[strArr[y]]++;
} else {
obj[strArr[y]] = 1;
}
}
return obj;
};
var mForN_2 = function(obj, objKeys) {
for (var z = 0; z < objKeys.length; z++) {
/* console.log(
"obj[objKeys[z]]: " +
obj[objKeys[z]] +
" obj[objKeys[z]] % 2: " +
eval(obj[objKeys[z]] % 2)
); */
if (eval(obj[objKeys[z]] % 2) == 1) {
oddCounter++;
}
// console.log("oddCounter: " + oddCounter);
}
return oddCounter <= 1;
};
var isset = function(obj) {
if (typeof obj === "undefined" || obj === null) {
return false;
} else {
return true;
}
};
var isPalindrom = function(str) {
// reverse original string
splitString = str.split("");
reverseArray = splitString.reverse();
joinArray = reverseArray.join("");
var checking = checkSpellingOfStr(str);
if (str == joinArray) {
strArr = str.split("");
// console.log("strArr: " + strArr);
objKeys = makeObjKeys(count, strArr);
// console.log("filled count before mForN: " + JSON.stringify(count));
// create array of keys in the count object
objKeys = Object.keys(count);
// console.log("objKeys: " + objKeys);
count = mForN(count, strArr);
// console.log("count after mForN: " + JSON.stringify(count));
return mForN_2(count, objKeys);
} else {
return 0;
}
};
var makeObjKeys = function(obj, arr) {
for (var x = 0; x < arr.length; x++) {
obj[arr[x]] = null;
}
return obj;
};
var checkSpellingOfStr = function(someStr) {
var formData = {
someWord: someStr
};
$.ajax({
type: "GET",
url: url,
data: formData,
success: function(result) {
if (!$.trim(result)) {
} else {
console.log(result);
$("#checkSpelling").html(result);
}
}
});
};
Start everything with the following call:
isPalindrom("mom") ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
In my example, I have a form and I listen for a button click as follows:
var palindromeTxt = document.getElementById("palindromeTxt").value;
var btn = document.getElementById("button");
btn.addEventListener("click", function (event) {
isPalindrom(palindromeTxt) ? demoP.innerHTML = "is pal" : demoP.innerHTML = "is not pal";
});
The following is the php for spell check:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(!empty($_REQUEST['someWord']))
{
$someWord = $_REQUEST['someWord'];
}
$pspell_link = pspell_new("en");
if (pspell_check($pspell_link, $someWord)) {
echo trim($someWord) . " is a recognized word in the English language";
} else {
echo "Your word is either misspelled or that is not a recognized word";
}
You will need pspell installed on your server, as well as adding extension=pspell.so to your php.ini
This is what I did, to get it running locally on my mac:
cd /Users/username/Downloads/php-5.6.2/ext/pspell
/usr/local/bin/phpize
./configure --with-php-config=/usr/local/php5-5.6.2-20141102-094039/bin/php-config --with-pspell=/opt/local/
make
cp ./modules/* /usr/local/php5-5.6.2-20141102-094039/lib/php/extensions/no-debug-non-zts-20131226
sudo apachectl restart
check your phpinfo file and you should see the following:
pspell
PSpell Support enabled
Live example

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"));

custom rules parser

I have a set of masks.
The masks look like this
'09{2,9}n(6)'
//read as 09
//[a number between 2 and 9]
//[a random number][repeat expression 6 times]
'029n(7,10)'
//read as 029
//[a random number][repeat expression between 7 and 10 times]
'029n(2,5){8,15}(7,10)n'
//read as 029
//[a random number][repeat expression between 2 and 5 times]
//[a random number between 8 and 15][repeat expression between 7 and 10 times]
//[a random number]
as an example expession 3 would work out as
'029n(4){4,9}(7)n'
'029nnnn{4,9}{4,9}{4,9}{4,9}{4,9}{4,9}{4,9}n
'029nnnn{5}{9}{4}{8}{5}{9}{9}n
'029nnnn5948599n'
'029023559485999'
I need to write a parser in javascript that can generate a string based on those rules.
Note that this is not validation, it is string generation.
Whats the best way to do this?
Trying out a custom parser. Use as,
var generator = new PatternGenerator('09{2,9}n(6)');
generator.generate(); // 096555555
generator.generate(); // 095000000
Checkout this example.
And the constructor function,
function PatternGenerator(pattern) {
var tokens = null;
this.generate = function() {
var stack = [];
tokens = pattern.split('');
// Read each token and add
while (tokens.length) {
var token = lookahead();
if (isDigit(token)) {
stack.push(consumeNumber());
}
else if (token == "n") {
stack.push(consumeVariableNumber());
}
else if (token == "(") {
var topObject = stack.pop();
stack.push(consumeRepetition(topObject));
}
else if (token == "{") {
stack.push(consumeVariableRangeNumber());
}
else {
throw new Error("Invalid input");
}
}
return stack.join('');
}
// [0-9]+
function consumeNumber() {
var number = "";
while (isDigit(lookahead())) {
number += consume();
}
return number;
}
// "n"
function VariableNumber() {
var number = generateRandomNumber();
this.toString = function() {
return Number(number);
};
}
function consumeVariableNumber() {
consume();
return new VariableNumber();
}
// {x, y}
function VariableRangeNumber(start, end) {
var number = generateRandomNumberBetween(start, end);
this.toString = function() {
return Number(number);
};
}
function consumeVariableRangeNumber() {
consume(); // {
var firstNumber = consumeNumber();
consume(); // ,
var secondNumber = consumeNumber();
consume(); // }
return new VariableRangeNumber(firstNumber, secondNumber);
}
// <expression>(x)
function Repeat(object, times) {
this.toString = function() {
var string = "";
for (var i = 0; i < times; i++) {
string += object;
}
return string;
};
}
// <expression>(x, y)
function RepeatWithRange(object, start, end) {
var times = generateRandomNumberBetween(start, end);
this.toString = function() {
return new Repeat(object, times).toString();
};
}
function consumeRepetition(object) {
consume(); // (
var firstNumber, secondNumber;
var firstNumber = consumeNumber();
if (lookahead() == ",") {
consume(); // ,
secondNumber = consumeNumber();
}
consume(); // )
if (typeof secondNumber == 'undefined') {
return new Repeat(objectToRepeat, firstNumber);
}
else {
return new RepeatWithRange(object, firstNumber, secondNumber);
}
}
// Helpers to generate random integers
function generateRandomNumber() {
var MAX = Math.pow(2, 52);
return generateRandomNumberBetween(0, MAX);
}
function generateRandomNumberBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function lookahead() {
return tokens[0];
}
function consume() {
return tokens.shift();
}
function isDigit(character) {
return /\d/.test(character);
}
}

Categories

Resources