Javascript / JQuery Conditional replace - javascript

I have a variable in javascript:
var myvar = "0711111111";
I bascially need to do a condition saying:
if (myvar's first character = '0') or (myvar's first character = '+') {
then ... replace the first character with 'somethingelse';
}

Please try this !
var myvar = "0711111111" , repWithChar = "x";
var firstChar = myvar.charAt(0);
if ((firstChar === "0") || (firstChar === "+")) {
console.log( myvar.replace(myvar.charAt(0), repWithChar) );
}
Output: x711111111

var myvar = "0711111111";
if(myvar[0] == "0" || myvar[0] == "+"){
myvar = myvar.substring(1);
}
or Use charAt()
if(myvar.charAt(0) == "0" || myvar.charAt(0) == "+"){
myvar = myvar.substring(1);
}
or use substring()
if(myvar.substring(0,1) == "0" || myvar.substring(0,1) == "+"){
myvar = myvar.substring(1);
}
Fiddle

var myvar = "0711111111";
if(myvar[0] == "0" || myvar[0] == "+"){
myvar[0] = "$"; // U can replace
}

var myvar = "0711111111";
if (myvar.charAt(0) == '0' || myvar.charAt(0) == '+') {
// Replace the char in pos 0 with desired char (now using '=')
myvar = myvar.replace(myvar.charAt(0), '=')
}
Output: "=711111111"

take the first character with myvar[0] and compare with the other two characters
var firstchar = myvar[0]; //or myvar.charAt(0) for ie7 and older support
if ( firstchar === '0' || firstchar === '+' ) {
// do stuff
myvar = myvar.replace( firstchar, 'X' ); // where X is the new character
}

Related

a regex or function to extract all the parameters passed to a function

I am looking to find the passed parameter to a function
say i already have hello as function and i have a STRING as following
hello(1,'434','hello,word',"h,g",{a:'b,u', l : { "sk" : "list", bk : 'u,93' }, c : 9},true)
Then upon that regex or function i should be able to find following 6 strings
'1'
'"434"'
'"hello,world"'
'"h,g"'
'{"a":"b,u","l":{"sk":"list","bk": "u,93"},"c":9}'
'true'
As per urs question you can do it like this:
x =Hello(1,'434','hello,word',"h,g",{a:'b,u', l : { "sk" : "list", bk : 'u,93' }, c : 9},true);
function Hello() {
for (i = 0; i <arguments.length; i++) {
console.log(arguments[i])
}
}
You can take help of argument object which is an Array-like object corresponding to the arguments passed to a function.
If that's a string then you might have to escape the double quotes first to result like
var x = "hello(1,'434','hello,word',\"h,g\",{a:'b,u', l : { \"sk\" : \"list\", bk : 'u,93' }, c : 9},true)";
and then you may invoke it like
Function(x)();
and in the hello function you should iterate over the arguments object's properties like
function hello(){
Array.prototype.forEach.call(arguments, prop => console.log(prop));
}
This is my workaround. It may be error-prone, but it should be faster than the eval solutions.
var extractParameters = function(str){
var ar = [];
if(typeof str === 'string' && str.length){
var chars = str.split(','), cl = chars.length;
var pushInto = function(n){
try {
ar.push(JSON.parse(chars[n]));
} catch(er){
ar.push(undefined);
}
};
for(var di, si, eg, fg, n = 0; n < cl; n++){
eg = chars[n].charAt(0);
fg = chars[n].charAt(chars[n].length - 1);
if(eg === fg && (eg === '"' || eg === "'")){
chars[n] = "\"" + chars[n].substring(1, chars[n].length - 1) + "\"";
}
di = chars[n].indexOf('"');
si = chars[n].indexOf("'");
if(((si === -1) && (di === -1)) || (eg === fg && (eg === '"' || eg === "'")) ||
(chars[n].charAt(0) === "{" && chars[n].charAt(chars[n].length-1) === "}" && (chars[n].match(/\{/g).length === chars[n].match(/\}/g).length))){
pushInto(n);
} else if(n < (cl-1)) {
chars[n] = chars[n] + ','+ chars[n+1];
chars.splice(n+1,1);
n--;
cl--;
continue;
}
}
}
return ar;
};
fiddle : https://jsfiddle.net/jv0328tp/16/

Evaluate string giving boolean expression in JavaScript

I have a string that contains Boolean logic something like:
var test = "(true)&&(false)&&!(true||true)"
What is a good way to evaluate this string in JavaScript to get the boolean value of false in this case
I know we could use eval() or new Function().. - but is that a safe approach?
I am guessing the other option would be to write a custom parser. Being a fairly new person to JS, would that be a lot of effort? I could not find any examples of parsers for Boolean logic expressions
Any other alternatives?
As long as you can guarantee it to be safe, I think you could use eval.
Maybe by treating it before doing an eval?
var test = "(true)&&(false)&&!(true||true)"
var safe = test.replace(/true/ig, "1").replace(/false/ig, "0");
var match = safe.match(/[0-9&!|()]*/ig);
if(match) {
var result = !!eval(match[0]);
}
Javascript has a ternary operator you could use:
var i = result ? 1 : 0;
Here, result is Boolean value either True or False.
So, Your question will be something like that after this operation.
(1)&(0)&!(1||1)
I hope you can better evaluate now this Boolean logic.
you can use eval,
Eg: eval("(true)&&(false)&&!(true||true)");
Try this code
function processExpression(expr)
{
while (expr.indexOf("(" ) != -1 )
{
expr = expr.replace(/\([\w|]+\)/g, function(matched){ return processBrace(matched)});
}
return expr = processBrace( "(" + expr + ")" );
}
function processBrace(str)
{
return str.substring(1).slice(0,-1).split(/(?=&|\|)/).map(function(value,index,arr){
if ( index != 0 && index%2 == 0 ) { return arr[index-1] + value } else if(index==0){return value;} else {return ""}
}).filter(function(val){return val.length > 0}).reduce(function(prev,current){
var first = Boolean(prev);
var operator = current.substring(0,2);
var operand = current.substring(2);
while ( operand.indexOf("!") != -1 )
{
var boolval = operand.match(/\w+/)[0] == "false"; //flip the value by comparing it with false
var negations = operand.match(/\W+/)[0];
operand = negations.substring(1) + boolval;
}
var second = operand == "true";
var output = operator == "&&" ? (first && second) : (first || second);
return output;
});
}
DEMO
function processExpression(expr)
{
while (expr.indexOf("(" ) != -1 )
{
expr = expr.replace(/\([\w|]+\)/g, function(matched){ return processBrace(matched)});
}
return expr = processBrace( "(" + expr + ")" );
}
function processBrace(str)
{
return str.substring(1).slice(0,-1).split(/(?=&|\|)/).map(function(value,index,arr){
if ( index != 0 && index%2 == 0 ) { return arr[index-1] + value } else if(index==0){return value;} else {return ""}
}).filter(function(val){return val.length > 0}).reduce(function(prev,current){
var first = Boolean(prev);
var operator = current.substring(0,2);
var operand = current.substring(2);
while ( operand.indexOf("!") != -1 )
{
var boolval = operand.match(/\w+/)[0] == "false"; //flip the value by comparing it with false
var negations = operand.match(/\W+/)[0];
operand = negations.substring(1) + boolval;
}
var second = operand == "true";
var output = operator == "&&" ? (first && second) : (first || second);
return output;
});
}
var example1 = "(true)&&(false)&&!(true||true)";
document.body.innerHTML += example1 + " -- " + processExpression(example1);
Try using "".match() in ternary operator condition
"(true)&&(true)&&!(true||true)".match(/false/ig)?false:true

Cannot read property length null error when used with regular expressions

I'm a javascript beginner doing some CodeWars.com questions. I came across this question and I'm stuck due to a "cannot read property length null" error. I've tried to look up that error and can't find what the problem is in my program.
The assignment is:
"Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contains any char."
And this is what I've written so far:
function XO(str) {
var x = "x";
var o = "o";
var numX = str.match(/x/gi).length;
var numO = str.match(/o/gi).length;
while(str.indexOf(x) > -1 || str.indexOf(o) > -1) {
if(numX == numO){
return true;
}
}
if (numX === -1 && numO === -1){
return true;
}
}
XO("xoxo");
The assignment also says that if there is neither an X or an O then the program should return true.
This will not give you that error. When there are no matches, the match function returns null and you cannot get the length of null. A few extra lines solves this issue.
function XO(str) {
var x = "x";
var o = "o";
var numX = 0;
var numO = 0;
var xMatch = str.match(/x/gi);
var oMatch = str.match(/o/gi);
if (xMatch) {
numX = xMatch.length;
}
if (oMatch) {
numO = oMatch.length;
}
while(str.indexOf(x) > -1 || str.indexOf(o) > -1) {
if(numX == numO){
return true;
} else {
return false;
}
}
if (numX === -1 && numO === -1){
return true;
} else {
return false;
}
}
console.log(XO("ddd"));
I think you are making this problem more complex than it has to be.
All you need to do is make the string lowercase(to account for case insensitive), traverse the string, and when it finds an x, add 1 to a counter, and when you find and o, decrease 1 from the counter.
If it ends at 0, you return true, else you return false. There's no need for regexes
function XO(str){
var count = 0;
str = str.toLowerCase();
for(var i = 0; i < str.length; i++){
if(str[i] === 'x') count++;
if(str[i] === 'o') count--;
}
return count === 0 ? true : false;
}
Yes you have to check the return value of match is not null before checking the length property. However
while(str.indexOf(x) > -1 || str.indexOf(o) > -1) {
if(numX == numO){
return true;
}
}
looks like an infinite loop if either string contains lower case 'x' or 'o' and there are a different number of each.
More simply:
function XO(str)
{ var matchX = str.match(/x/gi);
var matchY = str.match(/o/gi);
return (matchX && matchY) ? matchX.length == matchY.length : !matchX && !matchY;
}

Javascript Difference Between x=10; if(x) and if(x===10)

I understand that in terms of boolean
x = true;
if(x) //This is the same as if(x === True)
doSomething();
But if one were to set x to a number, then what does the if condition mean?
Does the condition mean if(x === true)? If so, why is that?
In javascript the below are falsey
false
undefined
null
0
""
NaN
Anything except the above are truthy, including numbers, except 0. So 10 is a truthy value and hence the if block, executes.
in short is as follows:
//!length = if(x.length);
var a; //undefined == if(!a) == !length
var b = ""; //void == if(!b)
var c = " "; //blank == if(c) == length
var d = "text"; //there == if(d) == length
var e = true; //true == true == if(e)
var f = false; //false == false == if(!f)
var g = null; //false == if(!g) == !length
var h = 0; //0 == if(!h)
var i = 1; //true == if(i)
var j = 0/0; //NaN == if(!j)
var k = document.body; // == if(k)
var l = document.getElementById("nothing"); // if(!l) == !length
Javascript is very flexible with regards to checking for "null" values. I'm guessing you're actually looking for empty strings, in which case this simpler code will work:
if(!blah){
Which will check for empty strings (""), null, undefined, false and the numbers 0 and NaN
var a; //undefined == if(!a) == !length
var b = ""; //void == if(!b)
var c = " "; //blank == if(c) == length
var d = "text"; //there == if(d) == length
var e = true; //true == true == if(e)
var f = false; //false == false == if(!f)
var g = null; //false == if(!g) == !length
var h = 0; //0 == if(!h)
var i = 1; //true == if(i)
var j = 0/0; //NaN == if(!j)
var k = document.body; // == if(k)
var l = document.getElementById("nothing"); // if(!l) == !length
consoletotal(l);
function consoletotal(bb){
consolea(bb);
consoleb(bb);
consolec(bb);
consoled(bb);
consolee(bb);
}
function consolea(bb){
if(bb){
console.log("yes" + bb);
}
}
function consoleb(bb){
if(bb===true){
console.log("true" + bb);
}
}
function consolec(bb){
if(bb===false){
console.log("false" + bb);
}
}
function consoled(bb){
if(!bb){
console.log("no" + bb);
}
}
function consolee(bb){
if(bb.length){
console.log("length" + bb);
}
}

Removing unwanted characters from textbox with JQuery

What I would like to get some input on is how to remove certain characters from a textbox (or textarea) with JQuery. I have the code in C# but I can´t seem to translate that to JQuery javascript. My problem is that I don´t know how to get the value from a textbox as a character array which I then can loop through and compare against a given set of unwanted characters.
This is how "far" I have come in JQuery:
$("input[type=text], textarea").change(function() {
// code here
});
This is my code in C#:
for (int i = 0; i < charArray.Length; i++)
{
current = charArray[i];
if ((current == 0x9) ||
(current == 0xA) ||
(current == 0xD) ||
((current >= 0x20) && (current <= 0xD7FF)) ||
((current >= 0xE000) && (current <= 0xFFFD)))
_validXML.Append(current);
}
return _validXML.ToString().TrimEnd((char)32, (char)160) ;
UPDATE:
I went with a combination of some answers below (I will upvote them) and my final JQuery looks like this and works:
$(document).ready(function() {
$(":text, textarea").change(function() {
var text = "";
var arr = $(this).val()
$.each(arr, function(i) {
var c = arr.charCodeAt(i);
if ((c == 0x9) ||
(c == 0xA) ||
(c == 0xD) ||
(c >= 0x20 && c <= 0xD7FF) ||
(c >= 0xE000 && c <= 0xFFFD))
{
text += arr.charAt(i);
}
});
$(this).val(text);
});
});
Thanks all!
Would't this be the case for regular expressions, like:
$("input[#type='text'], textarea").change(function() {
this.value = this.value.replace(/[^\w\d]+/gim,"");
});
Textarea:
<textarea id="item" name="item" rows="5" cols="80">Some text in here</textarea>
jQuery code:
var text = $('#item').val();
var newtext = "";
for (var i = 0; i < text.length; i++) {
var c = text.charCodeAt(i);
if ((c == 0x9) || (c == 0xA) || (c == 0xD) ||
(c >= 0x20 && c <= 0xD7FF) ||
(c >= 0xE000 && c <= 0xFFFD)) {
newtext += text[i];
}
}
$('#item').val(newtext);
This has actually very little to do with jQuery, methinks, except to access the text data and set it again.
You can use the charCodeAt() method combined with the length property of strings to loop through the characters in the string.
Something like:
$("input[type=text], textarea").change(function() {
var text = $(this).val()
for(var i = 0; i < text.length; ++i) {
var currentChar = text.charCodeAt(i);
// Do something with it...
});
My initial version used charAt(), but since it looks like you're dealing with Unicode code points, charCodeAt() is more appropriate.
Use an event observer (onkeydown / onkeypress / onkeyup) on the input/textarea, get the key pressed, if the key is an unwanted character, stop the event from happening.
$("input[type=text], textarea").observe('keypress', function(e) {
var keynum;
if(window.event)
{
keynum = e.keyCode
}
else if(e.which)
{
keynum = e.which
}
if(keynum == '13' || keynum == 'something else' || [...])
{
Event.stop(e);
}
});
to get the value of textarea try:
$('input[type=textarea]').change(function(){
var value = $(this).val();
...........
});
to remove unwanted character try this example .. i copy from the jquery documentation (jQuery.grep())
var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];
$("div").text(arr.join(", "));
arr = jQuery.grep(arr, function(n, i){
return (n != 5 && i > 4);
});
$("p").text(arr.join(", "));
arr = jQuery.grep(arr, function (a) { return a != 9; });
$("span").text(arr.join(", "));
I prefer to stop the character from getting entered in the first place, using this type of javascript function (from my shady past):
each input control has something like this on it:
onkeypress='checkKey(this,"a-zA-Z0-9","N","10");'
the function looks like:
//****************************************************************************
// Function: checkKey()
// Author: Ron Savage
// Date: 10-11-2004
//
// Description: This function tests reg exp syntax.
//****************************************************************************
function checkKey(textControl, reExpr, allCaps, maxlen)
{
popupMessage.hide();
keyStr = String.fromCharCode(event.keyCode);
textLength = textControl.value.length;
if (allCaps == 'Y')
{
keyStr = keyStr.toUpperCase();
event.keyCode = keyStr.charCodeAt(0);
}
if ( reExpr != '' )
{
reString = '[^' + reExpr + ']';
re = new RegExp(reString, 'g');
//alert('RE: ' + reString);
result = keyStr.match(re);
if (result)
{
beep();
event.returnValue = false;
showPopupMessage(textControl, result.toString() + ' not allowed!');
}
}
if ( textLength > maxlen )
{
beep();
event.returnValue = false;
showPopupMessage(textControl, 'Max length [' + maxlen + '] exceeded!');
}
//alert('Key: ' + keyStr + ' code: ' + event.keyCode);
}

Categories

Resources