javascript always return false in my case - javascript

I am writing code for recursion. And here is my code.
Here, what I am trying to do is, if string has ' then replace it with HTML quotes and calling function recursively until all ' have been replaced.
But this is always returning me false. When I alert var a. If I not use return false then it returns undefined. Any clue what is the wrong here?
var a = replaceqt(" hello's there 'how are you?' ");
console.log(a);
function replaceqt(object) {
var indexc = object.indexOf("'");
var next = object.charAt(indexc + 1);
var prev = object.charAt(indexc - 1);
if (indexc == 0) {
object = object.replace("'", "‘");
} else if (parseInt(prev) >= parseInt(0) && parseInt(prev) <= parseInt(9)) {
object = object.replace("'", "'");
} else if (next == " ") {
object = object.replace("'", "’");
} else if (prev == " ") {
object = object.replace("'", "‘");
} else {
object = object.replace("'", "’");
}
indexc = object.indexOf("'");
if (indexc > -1) {
replaceqt(object);
return false;
} else {
return object;
}
}

Because you are returning false whenever there is a second call. Should return the result of recursive invocation instead.
var a = replaceqt(" hello's there 'how are you?' ");
console.log(a);
function replaceqt(object) {
var indexc = object.indexOf("'");
var next = object.charAt(indexc + 1);
var prev = object.charAt(indexc - 1);
if (indexc == 0) {
object = object.replace("'", "‘");
} else if (parseInt(prev) >= parseInt(0) && parseInt(prev) <= parseInt(9)) {
object = object.replace("'", "'");
} else if (next == " ") {
object = object.replace("'", "’");
} else if (prev == " ") {
object = object.replace("'", "‘");
} else {
object = object.replace("'", "’");
}
indexc = object.indexOf("'");
if (indexc <= -1) {
return object;
}
return replaceqt(object);
}
BTW you don't need parseInt(num) if num is a number say 0 or 9.

You need to replace
if (indexc <= -1){
return object;
}else{
replaceqt(object); return false;
}
with
if (indexc <= -1){
return object;
}else{
return replaceqt(object);
}
In your original code, the return value of replaceqt(object) is discarded when indexc >= 0.

You should try using .split and .join functions to simplify your code.
For a simple find-replace all, you can do this:
var sentence = "I hate spaces."
var charToFind = " ";
var replacement = "-";
var afterSplit = sentence.split(charToFind) // ["I", "hate", "spaces"]
var result = afterSplit.join(replacement) // "I-hate-spaces"
Your example is more complex than a find replace, because you need to keep track of left and right quotes.
To get around that, we can figure out if it's even or odd using the index in the array.
var someString = "My 'name' is 'Ryan'... I 'think'."
function replaceQuotesFor (str) {
return str
.split("'")
.map(function (str, index) {
var quote = index % 2 === 1
? '‘'
: '’'
return (index === 0)
? str
: quote + str
})
.join('')
}
console.log('Before:', someString)
console.log('After:', replaceQuotesFor(someString))
I stopped using for loops and modifying indices, because it made debugging frustrating.
I hope these functions help simplify your code and help you in the future!

Related

Increment digit part of string in JavaScript

I have a string that contains digit at the end. I want to increase the digit part by 1 when some actions happened.
e.g.
var myString = 'AA11111'
increaseStringValue(myString)
# myString new value => 'AA11112'
also how can I increase chars when string value reached to 'AA99999' so new value of string will be 'AB11111'?
You can split char and digit parts so you can handle them separately.
like:
function increaseStringValue(str){
let charPart = str.substring(0,2);
let digitPart = str.substring(2);
digitPart = +digitPart+1
if(digitPart >= 99999){
digitPart = 11111;
if(charPart[1] == 'Z'){
if(charPart[0] == 'Z'){
throw 'Overflow happened'
}
charPart = String.fromCharCode(charPart.charCodeAt(0)+1) + 'A'
}else{
charPart = charPart[0] + String.fromCharCode(charPart.charCodeAt(1)+1)
}
}
return charPart + digitPart;
}
increaseStringValue('AA11111'); // 'AA11112'
increaseStringValue('AA99999'); // 'AB11111'
increaseStringValue('AZ99999'); // 'BA11111'
increaseStringValue('ZZ99999'); // Exception: Overflow happened
This links will be helpful for you:
ASCII CODES
what is a method that can be used to increment letters?
Edit:
Following function will be suite for unknown length string with dynamic position of char and digit.
function increaseStringValue(str) {
let charOverFlowed = true;
let result = ""
for (let i = str.length - 1; i >= 0; i--) {
let currentChar = str[i];
if ('123456789'.indexOf(currentChar) !== -1) {
if (charOverFlowed) {
currentChar = +currentChar + 1
charOverFlowed = false;
}
if (currentChar > 9) {
currentChar = 1;
charOverFlowed = true;
}
} else if (charOverFlowed) {
currentChar = String.fromCharCode(currentChar.charCodeAt(0) + 1)
charOverFlowed = false;
if (currentChar > 'Z') {
if(i == 0){
throw 'Overflow Happened'
}
currentChar = 'A'
charOverFlowed = true
}
}
result = currentChar + result;
}
return result;
}
increaseStringValue('AAAACA')
// "AAAACB"
increaseStringValue('AAAACA1111')
// "AAAACA1112"
increaseStringValue('A1')
// "A2"
increaseStringValue('Z')
// Uncaught Overflow Happened
increaseStringValue('A1999')
// "A2111"
function increaseStringValue(myString){
return myString.replace(/\d+/ig, function(a){ return a*1+1;});
}
console.log(increaseStringValue("asg61"));
And for next question:
function increaseStringValue(myString){
return myString.replace(/(A)(\d+)/ig, function(a, b, c){
var r = c*1+1; return r==99999+1?"B11111":"A"+r;
});
}
console.log(increaseStringValue("AA99999"));
And Whole way:
function increaseStringValue(myString){
return myString.replace(/([a-e])(\d+)/ig, function(a, b, c){
var r = c*1+1; return r==99999+1?String.fromCharCode(a.charCodeAt(0)+1)+"11111":b+r;
});
}
console.log(increaseStringValue("AB99999"));
Please find the snippet useful. If this is what you are expecting.
let stringNum = 'AA11111';//initialise string
let clickTriggered = ()=>{
let startString = "AA";
let newNum = ()=>{
let numberPart = stringNum.split("AA")[1];
let lastChar = stringNum[stringNum.length-1];
return Number(numberPart) != NaN || Number(numberPart) <= 99999 ? Number(numberPart)+1 : 11111;
};
stringNum = `${startString}${newNum()}`
console.log(stringNum)
}
<h1 onclick="clickTriggered()">click here</h1>
You can use String#replace and provide your increment logic in the function callback of the string#replace.
const increaseStringValue = (str) => str.replace(/\d+$/, n => n === '99999' ? 11111 : +n + 1);
console.log(increaseStringValue('AA99999'));
console.log(increaseStringValue('AA11315'));
console.log(increaseStringValue('AA11111'));
I solve this with this solution
let app = new Vue({
el: '#app',
data: {
text: "AA995"
},
methods: {
addOneString: function(str) {
var alphabet = 'abcdefghijklmnopqrstuvwxyz',
length = alphabet.length,
result = str,
i = str.length,
value = str;
while(i >= 0) {
var last = str.charAt(--i),
next = '',
carry = false;
if (isNaN(last)) {
index = alphabet.indexOf(last.toLowerCase());
if (index === -1) {
next = last;
carry = true;
}
else {
var isUpperCase = last === last.toUpperCase();
next = alphabet.charAt((index + 1) % length);
if (isUpperCase) {
next = next.toUpperCase();
}
carry = index + 1 >= length;
if (carry && i === 0) {
var added = isUpperCase ? 'A' : 'a';
result = added + next + result.slice(1);
break;
}
}
}
else {
next = +last + 1;
if(next > 9) {
next = 0;
carry = true;
}
if (carry && i === 0) {
result = '1' + next + result.slice(1);
break;
}
}
result = result.slice(0, i) + next + result.slice(i + 1);
if (!carry) {
break;
}
}
console.log("result",result);
if (value !== result ) this.text = result;
}
}
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div class="container" id="app">
<button #click="addOneString(text)">Add one</button>
</br>
<p> {{text}} </p>
</div>

else if help in Javascript

I want to take two strings and returns the longer string. If both strings have the same length, then the function should return the string 'TIE'. I am very new to javascript
function getLongerString(str1,str2)
{
var a = console.log("str1");
var b = console.log("str2");
if(a.length==b.length)
{
long = "TIE";
}
else if(a.length>b.length)
{
long = a;
}
else
{
long = b;
}
console.log(long);
}
The issue is with this two lines
var a = console.log("str1").value;
var b = console.log("str2").value;
Also no need to create intermediate variable a & b
It does not make anything logical
function getLongerString(str1, str2) {
let long = "";
if (str1.length === str2.length) {
long = "TIE";
} else if (str1.length > str2.length) {
long = str1;
} else {
long = str2;
}
console.log(long);
}
getLongerString("Hello World", "New World")
Check this out:
var pre = onload, getLongerStr; // for use on other loads
onload = function(){
if(pre)pre(); // change var name if using technique on another page
function getLongerStr(str1, str2){
var s1 = str1.length, s2 = str2.length;
if(s1 === s2){
return 'TIE';
}
else{
return s1 > s2 ? str1 : str2;
}
}
console.log(getLongerStr('what', 'cool'));
console.log(getLongerStr('lame', 'yes'));
console.log(getLongerStr('absolutely', 'pointless'));
}

javascript recursion first char of string1 then last char of string2

Suppose I have two strings, n1 = abc and n2 = xyz. How can I print "azbycx" recursively?
Here is my code. I am practicing string manipulations and I can't seem to find a solution to this. I Googled already and can't seem to find one.
document.write(practice("abc","xyz"));
function practice(n1,n2){
if(n1.length==0){return n2;}
if(n2.length==0){return n1;}
return n1.substring(0,1) + practice(n2.charAt(n2.length-1),n1.substring(1));
}
It prints only "azc" :(
function practice(n1,n2){
console.log(n1);
console.log(n2);
if(n1.length==0){return n2;}
if(n2.length==0){return n1;}
return n1[0]+n2[n2.length-1] + practice(n1.substring(1), n2.substring(0, n2.length-1));
}
function practice(n1,n2){
if(n1.length==0){return n2;}
if(n2.length==0){return n1;}
if (n2.length > n1.length) {
return n2.charAt(n2.length-1) + practice(n1, n2.substring(0, n2.length-1));
}
else {
return n1.charAt(0) + practice(n1.substring(1), n2);
}
}
var practice = function(n1,n2) {
var _charA = n1.charAt(0)
var _charB = n2.charAt(n2.length-1)
var _res = "";
if(_charA != "" || _charB != "") {
_res = practice(n1.substring(1,[n1.length]),n2.substring(0,[n2.length-1]))
}
return _charA + _charB + _res;
}
practice("abcd", "uvwxyz")
//output - azbycxdwvu
This would do what you like it to do:
function practice(n1,n2){
if(n1.length==0 && n2.length==0)
return "";
return n1.substr(0,1) + n2.substr(n2.length-1, 1) +
practice(n1.substr(1, n1.length-1), n2.substr(0, n2.length-1));
}
jsfiddle here: http://jsfiddle.net/gt7fsb7g/

how to get specific last decimal float value

var fNum = parseFloat("32.23.45"); results in 32.23 but I need the string from last decimal point: 23.45
For example, the following strings should return the following values:
"12.234.43.234" -> 43.234,
"345.234.32.34" -> 32.34 and
"234.34.34.234w" -> 34.34
A fairly direct solution:
function toFloat(s) {
return parseFloat(s.match(/\d+(\.|$)/g).slice(-2).join('.'));
}
For example:
toFloat("32.23.45") // 23.45
toFloat("12.234.43.234") // 43.234
toFloat("345.234.32.34") // 32.34
toFloat("234.34.34.234w") // 34.34
Update: Here's an alternative version which will more effectively handle strings with non-digits mixed in.
function toFloat(s) {
return parseFloat(s.match(/.*(\.|^)(\d+\.\d+)(\.|$)/)[2]);
}
The following will do exactly what you would like (I'm presuming that the last one should return 34.234, not 34.24).
alert (convText("12.234.43.234"));
alert (convText("345.234.32.34"));
alert (convText("234.34.34.234w"));
function convText(text) {
var offset = text.length - 1;
var finished = false;
var result = '';
var nbrDecimals = 0;
while(!finished && offset > -1) {
if(!isNaN(text[offset]) || text[offset] === '.') {
if(text[offset] === '.') {
nbrDecimals++;
}
if(nbrDecimals > 1) {
finished = true;
} else {
result = text[offset] + result;
}
}
offset--;
}
return result;
}

how to make function return more than one value

This is my code:
var Evalcard = function(number) {
if (number == 1) {
this.name = "Ace";
this.value = 11;
}
else if (number == 11) {
this.name = "Jack";
this.value = 10;
}
else if (number == 12) {
this.name = "Queen";
this.value = 10;
}
else if (number == 13) {
this.name = "King";
this.value = 10;
}
return {this.name,this.value};
I'm pretty sure this return statement is not correct. How do you make a function return more than one value? Any help at all would be great.
In this case, you probably want to return either an array or an object literal:
return { name: this.name, value: this.value };
// later: EvalCard(...).name; EvalCard(...).number;
return [ this.name, this.value ];
// later: EvalCard(...)[0]; EvalCard(...)[1];
How about this:
return [this.name, this.value];
You could pass an object literal as you came so close to doing:
return { name:this.name, value:this.value };
or you could pass an array:
return [this.name, this.value];
Of course if your code is executed in the global context, you'll be setting name and value on the window object. If you're using Evalcard as a constructor, you wont need a return statement, the object being created will automatically be set:
var e = new Evalcard(1);
console.log(e.name); //outputs "Ace" if you remove the return statement.
Try:
return [this.name, this.value];
Try this...
function xyz() {
...
var x = 1;
var y = 'A';
return [x, y];
}
var a = xyz();
document.write('x=' + a[0] + ' and y = ' + a[1]);
Working example: http://jsfiddle.net/CxTWt/
var Evalcard = function(number) {
var evalName, evalValue;
if (number == 1) {
evalName= "Ace";
evalValue = 11;
}else if (number == 11) {
evalName = "Jack";
evalValue = 10;
}else if (number == 12) {
evalName= "Queen";
evalValue= 10;
}else if (number == 13) {
evalName= "King";
evalValue = 10;
}
return {name: evalName, value: evalValue};
}
alert(Evalcard(1).name+" "+Evalcard(1).value);
You need to change it to return an array or give keys to the object you are returning
So
return [this.name,this.value];
Or
return {name:this.name,value:this.value};
I would return an object:
return {key1:value1, key2:value2}
Then you can reference it like so:
myReturn.key1;
You can return it in a number of different ways:
Array
return [this.name,this.value];
Object
return {first:this.name, second:this.value};
String
return this.name+":"+this.value;

Categories