I've been looking for an answer by looking at other posts but I couldn't find anything directly usable for my script (yet it might also be my ignorance toward JavaScript...)
I'm using this script to transliterate OnBlur from a foreign language's script to the Latin alphabet :
<script>
function separation() {
var str = document.getElementById().value;
var res1 = str.charAt(0);
var res2 = str.charAt(1);
var res3 = str.charAt(2);
document.getElementById().innerHTML = res1+res2+res3;
}
var syllable_1 = {
'김' : 'Kim ',
'이' : 'Lee ',
'야' : 'Ya',
}
var syllable_2 = {
'김' : 'gim',
'이' : 'i',
'야' : 'ya',
}
function hangul_to_roman(hangul) {
return syllable_1[hangul.charAt(0)] + syllable_2[hangul.charAt(1)] + ( hangul.length >= 3 ? "-" + syllable_2[hangul.charAt(2)] : "" );
}
</script>
<input type="text" id="ttt" value="김김이" onBlur="document.getElementById('demo').value = hangul_to_roman(document.getElementById('ttt').value)" style="text-transform: capitalize">
<input type="text" id="demo" readonly>
Here you have the same script in Fiddle : http://jsfiddle.net/LGRAq/6/
The first input field contains what's supposed to be transliterated and the second shows that transliteration; however it prints NaN when removing what's inside the first input field and I'd like to know how to remove it.
Is there anyone who would know how to proceed ?
Thank you very much for your help !
When hangul.charAt(…) is not contained in your syllable map, the property access will yield undefined. Adding two undefineds together will make a NaN. You can prevent that from showing up by using the empty string as a default value for the lookup:
function hangul_to_roman(hangul) {
return (syllable_1[hangul.charAt(0)] || "")
+ (syllable_2[hangul.charAt(1)] || "")
+ (hangul.length >= 3 ? "-" + (syllable_2[hangul.charAt(2)] || "") : "");
}
Bro, We could use this way to remove the NaN from appearing too.
var str = document.getElementById().value;
var res1 = str.charAt(0);
var res2 = str.charAt(1);
var res3 = str.charAt(2);
var res4 = res1+res2+res3;
if(!isNaN(res4))
document.getElementById().innerHTML = res4;
Related
So, I am trying to create a DNA to RNA sequence converter, but it isn't really displaying when I try to get the values and change them sequentially. I.E., when you type certain letters like ATG they will convert into UAC but in that specific order. Is there a way to? I've already tried an array but it isn't working.
JS:
var dna = document.getElementById("input1").value;
var rna = [];
var aminoacid;
function replace(){
if (dna.indexOf('a') > -1)
{
rna.push("u");
} else if(dna.indexOf('t') > -1){
rna.push("a");
} else if(dna.indexOf('c') > -1){
rna.push("g");
}
else if(dna.indexOf('g') > -1){
rna.push("c");
}
}
document.getElementById("total").innerHTML = rna;
HTML:
<input style="top: -350px;" placeholder="Type DNA's value..." onclick="onClick();" id="input1">
<button type="button" onclick="getInputValue();" id = "button1" style = "position: relative; z-index: 100; top: -300px; left: -200px;">Get RNA</button>
This should be what you are looking for:
const input = document.querySelector('#input1').value,
total = document.querySelector('#total');
let rna = input.replaceAll(/[atcg]/g, e =>
e == 'a' ? 'u' :
e == 't' ? 'a' :
e == 'c' ? 'g' :
e == 'g' ? 'c' :
' '
);
total.textContent = rna;
You can use String.prototype.replace() for this.
Replace docs
For example:
let DNA = 'ATG'
DNA = DNA.replace('A', 'U');
DNA = DNA.replace('T', 'A');
DNA = DNA.replace('G', 'C');
console.log(DNA);
You have several problems:
You are getting the value of the input immediately (before anyone has
had a chance to enter anything.
You are attempting to produce the output immediately (your code that
shows the result is outside of the function).
You are trying to directly show an array, rather than the contents of
the array.
Because you are using else if, your value will only be checked for,
at most, one value.
Is this what you are after?
var dna = document.getElementById("input1");
var rna = [];
var aminoacid;
function replace(){
let val = dna.value;
if (val.indexOf('a') > -1) {
rna.push("u");
}
if(val.indexOf('t') > -1){
rna.push("a");
}
if(val.indexOf('c') > -1){
rna.push("g");
}
if(val.indexOf('g') > -1){
rna.push("c");
}
document.getElementById("total").textContent = rna.join("");
}
<input placeholder="Type DNA's value..." id="input1">
<button type="button" onclick="replace();" id = "button1">Get RNA</button>
<div id="total"></div>
My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe#abc.com then I should output j*****e#abc.com.
var maskPII = function(S) {
var ans = "";
if(S.includes("#")){
S = S.toLowerCase();
var parts = S.split("#");
var first = parts[0];
for(var i=0;i<parts[0].length;i++){
if(i!=0 && i!=parts[0].length - 1)
first[i] = '*';
}
ans = first +"#" +parts[1];
}else{
}
return ans;
};
However in my loop I can't change the characters to asterisks.
After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?
To answer your question... javascript allows you access values of a string using [] indexing.. but that is read only access... you cannot insert/replace values using that operator.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
When using bracket notation for character access,
attempting to delete or assign a value to these properties will not succeed.
The properties involved are neither writable nor configurable.
(See Object.defineProperty() for more information.)
You need to extract the values you want to keep from the existing string and build up a new string as noted in other answers...
Well, this's what you're looking for, and this will be the output j*****e#abc.com.
var ans = "";
var S = "johndoe#abc.com"; //example
S = S.toLowerCase();
var parts = S.split("#");
var first = "";
for(var i = 0; i < parts[0].length; i++){
if(i != 0 && i != parts[0].length - 1){
first += '*';
}else{
first += parts[0][i];
}
}
ans = first +"#"+ parts[1];
console.log(ans);
Here is the code with your approach:
var maskPII = function(S) {
var ans = "";
if(S.includes("#")){
S = S.toLowerCase();
var parts = S.split("#");
var first = parts[0][0];
for(var i=0;i<parts[0].length;i++){
if(i!=0 && i!=parts[0].length - 1)
first += '*';
}
ans = first + parts[0][parts[0].length - 1] +"#" +parts[1];
}else{
}
return ans;
};
But if i were you i would use:
var mail = "johndoe#abc.com";
mail = mail.replace(/(?<=.)(.+?)(?=.#)/gi, '*'.repeat(mail.split('#')[0].length - 2));
console.log(mail);
You can use the bracket notation on a string (like an array) to get the character at a specific index, but you can't use this to change characters. So first[i] = '*' in your code wont do anything.
Strings in JavaScript are immutable. This means that if you want to change a string, a new string instance will be created. This also means that when you change a string in a for-loop, it can impact performance. (Although in this case the difference wont be noticeable.
)
I would use this code:
function maskPII(str) {
const indexOfAt = str.indexOf('#');
if (indexOfAt <= 2) {
return str;
}
return str[0] + '*'.repeat(indexOfAt - 2) + str.substring(indexOfAt - 1);
}
const email = 'johndoe#abc.com';
console.log(email);
console.log(maskPII(email));
It will look for the index of the # sign. If the index is less or equal than 2, (when not found the index will be -1) it will return the original string.
Otherwise it will get the first character, calculate the amount of asterisks needed (index of the # sign -2) and repeat those and then add the rest of the original string.
I have a function in PHP that gets a number inserted into a text input and converts it to a float, with comma separator for decimals.
After that, the number is registered in the database.
Now, I need to make something with JavaScript (or jQuery), that does the same kind of convertion.
$num = $_POST['precoItem'];//get the input value
$precoAd = tofloat($num);//convert it to float
$precoFinal = number_format($precoAd, 2, ',', '');//remove any 'dots' or 'spaces'
The PHP function toFloat() is this one:
function tofloat($num) {
$dotPos = strrpos($num, '.');
$commaPos = strrpos($num, ',');
$sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
if (!$sep) {
return floatval(preg_replace("/[^0-9]/", "", $num));
}
return floatval(
preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . ',' .
preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
);
}
For example, the final number will not have dots or spaces, only commas: Ex.: 45354,85 (45.354,85)
My JS knowledge is limited. I tried using things like:
var n = +$precoFinal;
var n = Number($precoFinal);
var n = parseFloat($precoFinal);
Why people like to downvote so much... Are you really gonna say that my question didn't had any research? Rly?
Try this:
var str = '45.354,85';
var num = str.split(/[\s.]+/).join('');
num = parseFloat(num.replace(",","."));
console.log(num);
I have some jQuery code where +$(...) is used in many places. The code does not work without the + part, when doing just $(...).
I couldn't find any explanation through Google. I'd appreciate any guidance if possible.
function calculate() {
var a = +$('#a').val(); // what is +$ ?
var b = +$('#b').val();
var c = b * 108.40;
//etc
}
+$() is actually two operations, where first $() runs to grab your input and then + coerces whatever the value of the input is into a number.
Here's a breakdown of what is happening:
var valueA = $('#a').val(); // "123"
var numberA = +valueA; // 123
console.log('valueA is a ' + typeof valueA); // 'valueA is a string'
console.log('numberA is a ' + typeof numberA); // 'numberA is a number'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="a" value="123"/>
sorry i couldn't think of better title ! plus my english sucks
her is my first plugin (basically i repackaged some js code as a plugin )
it adds a comma , separator to value every 3 digit , when someone types something inside textfield
(function($){
$.fn.num = function(userop){
var options = $.extend( {seperator:','} , userop );
$(this).keyup(function(e) {
var num = $(this).val();
var nStr = num + '';
nStr = nStr.replace( /\,/g, "");
var x = nStr.split( '.' );
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while ( rgx.test(x1) ) {
x1 = x1.replace( rgx, '$1' + options.seperator + '$2' );
}
$(this).val( x1 + x2 );
})
}
})(jQuery);
$('.number_input').num();
but problem is if i put 123456 in my textfield
var n = $('.number_input').val();
console.log(n);
will return 123,456
which is fine but it suppose to be a numeric value and each time user has to extract commas manually
by running it trough something like
n = Number($.trim(n.replace(/\,/g,'')));
is there any way to add this line to my plugin so it gets executed when someone runs .val() on textfild ?
basically i want to write comma remover once not every single time that i get each effected textfield value
If you change the default .val() method with the combination of the .data(), you'll be able the do what you want. Note that change .val() can have undesired effect (mostly when user try to override .val() aswell...)
Anyway, the first thing to do is give a data to every element that are active number. So in you init, add this code :
this.data('__numered', true);
Now we can detect if the element as a formatting.
Then here come the tricky part : overriding.
You'll have to save the old .val() method :
$.fn.__val = $.fn.val;
Then recreate .val() but check if its a numbered item :
$.fn.val = function(set){
if(typeof set === 'undefined'){
if(this.first().data('__numered'))
return Number($.trim(this.first().__val().replace(/\,/g,'')));
else
return this.first().__val();
}else
return this.__val(set)
}
Fiddle : http://jsfiddle.net/Tw77J/1/
First of all
I think I'm suggesting a better way to do what you are asking, instead of directly answering.
If you use, my solution, your plugin gives the users the option of getting what they want. (You cant predict what users need)
My Solution:
You can add this simple code:
if (userop == 'val') {
return Number($.trim($(this).val().replace(/\,/g, '')));
}
So your plugin would become:
(function ($) {
$.fn.num = function (userop) {
if (userop == 'val') {
return Number($.trim($(this).val().replace(/\,/g, '')));
}
var options = $.extend({
seperator: ','
}, userop);
$(this).keyup(function (e) {
var num = $(this).val();
var nStr = num + '';
nStr = nStr.replace(/\,/g, "");
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + options.seperator + '$2');
}
$(this).val(x1 + x2);
});
};
})(jQuery);
Remember, you are the creator of the plugin, and you can impose some rules for the developers using your plugin.
That said, ask your users to use $('selector').num('val'); to get the value without commas, and $('selector').val(), if they want it with comma.
So to brush up:
Use $('selector').num('val'); // with comma
Use $('selector').val(); // without comma
Put that in readme file or any document file.
Live demo!
Also, don't forget me to add me as a contributor to the plugin, If my answer helped you ;)