Why my method is not reversing the string [duplicate] - javascript

This question already has answers here:
How do you reverse a string in-place in JavaScript?
(57 answers)
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
(10 answers)
How do I split a string into an array of characters? [duplicate]
(8 answers)
Closed 8 days ago.
I know there are many other ways to reverse a string in JS but I wrote this and it is not working and I want to understand why. Mine only has two extra parameters so I can tell it to reverse from here to there.
function strRev(str, startRev, endRev) {
while (startRev < endRev) {
let temp = str[startRev];
str[startRev] = str[endRev];
str[endRev] = temp;
startRev += 1;
endRev -= 1;
}
return str;
}
And usage:
let str = "STACK";
strRev(str, 0, str.length -1 );
But what I get as result is the same original string. I don't understand why.
It works when I trace it on paper.

You can not set the character of a string using the index with bracket notation.
To do what you are trying to do, you need to use an array and not a string.
function strRev(orgStr, startRev, endRev) {
const str = Array.from(orgStr); // orgStr.split('');
while (startRev < endRev) {
let temp = str[startRev];
str[startRev] = str[endRev];
str[endRev] = temp;
startRev += 1;
endRev -= 1;
}
return str.join('');
}
let str = "STACK";
console.log(strRev(str, 0, str.length - 1));

Your algorithm is correct, but you need to change how you modify the string
Unfortunately you can't poke individual characters into a string, like you are trying to do.
Doubly unfortunately, trying to do so does not cause an error in Javascript.
function strRev(str, startRev, endRev) {
while (startRev < endRev) {
str = str.slice(0, startRev) + str[endRev] + str.slice(startRev + 1, endRev) + str[startRev] + str.slice(endRev + 1)
startRev += 1;
endRev -= 1;
}
return str;
}
let str = "STACK";
console.log(strRev(str, 0, str.length - 1));

Related

What does "<+" mean in this code? [duplicate]

This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Closed 5 years ago.
I encountered this strange supposed operator and am having trouble figuring out what it is. Any ideas?
var laugh = function(num){
var string="";
for (i=0; i<+num; i++) {
string+="ha";
}
return string + "!";
};
console.log(laugh(10));
One of the purposes of the + sign in JS is to parse the right part into the number.
const str = '4';
console.log(str + 5); // Concatenared as strings
console.log(+str + 5); // Sums the numbers
In your case you have an statement i < +num, which just parses num into number and i compares with it. If your num is a number, this will do nothing.
Look. I have used '10' instead of 10 and it still works, because the given string is parsed into number.
var laugh = function(num) {
var string="";
for (var i = 0; i < +num; i++) {
string+="ha";
}
return string + "!";
};
console.log(laugh('10'));
<+ is not an operator. You may interpret it simply as for (i=0; i < +num; i++) where + is the unary plus operator. The unary plus operator will coerce num into a number.
For example, if the value passed to num was "100" (as a String), the unary plus operator would coerce it to 100 (a Number).
MDN contains some examples of unary plus and other arithmetic operators.
This is the way this is parsed;
i < +num
In other words, num is being coerced to an integer before < is run on it.
There is no <+. They are parsed as separate symbols.

Number format with comma and decimal points [duplicate]

This question already has answers here:
How to format numbers as currency strings
(67 answers)
Closed 6 years ago.
I have tried using Number(x).toLocaleString(), but this only gives me 10,000.
When I use parseFloat(row.profit).toFixed(2) it gives me 10000.00. I tried combining parseFloat(Number(row.profit)toLocaleString()).toFixed(2) But not give me the desired output which should be 10,000.00.
How can I achieve this?
You can use a quick hack by testing if . is present in your locale string or not :
function localeFormat(x) {
var num = Number(x).toLocaleString();
if (num.indexOf("/.") > 0) {
num += ".00";
}else{
var n = parseFloat(x).toFixed(2).toString();
num = Number(n).toLocaleString();
}
return num;
}
var strs = ["10000", "10000.45", "10000.45768"];
for(var i = 0; i < strs.length; i++){
console.log(strs[i] + " -> " + localeFormat(strs[i]));
}

JS for-loop how to get the first value

I'm sorry for the dumb question. I've been trying to do this for hours now, and i really can't get it to work. So i have a for-loop that loops though some numbers.
But it doesn't take the first value(71990000).
How can this be achieved?
This is what i've got so far:
var minNr = 0000;
var maxNr = 10000;
var prefix = 7199;
function Nummer(min,max)
{
var regex = /^(\d{2})\1$/;
var guld_nr;
for(guld_nr = minNr; guld_nr < maxNr;)
{
if(regex.test(guld_nr))
{
$(".resultat").append(prefix + "" + guld_nr + "<br>");
}
guld_nr++;
}
}
The output is this:
71991010
71991111
71991212
71991313
But i also need the number: 71990000
How can i do that ?
It's because your regex is rejecting the number 0; the first time through the loop, minNr has the numeric value 0 (setting it to 0000 doesn't help; it's just a fancy way of saying 0). The regex expects two digits followed by the same pattern, but what you're giving it is the string '0'.
You could set minNr to be a string instead on the first pass through ('0000'), and this will solve the problem for '0000', but you will miss '0101', '0202', etc. (which will convert to the strings '101', '202', and so on.)
One solution would be to zero pad the string representation of your number. The following function will take any number and left zero pad it to fit a given width:
function zeropad(n, w) {
n = String(n);
while(n.length < w) n = '0' + n;
return n;
}
You can use it to convert minNr for the regex:
regex.test(zeropad(guld_nr, 4))
Also note that Number is a built-in object wrapper for literals in JavaScript (all of the primitives have object wrappers: Number, Boolean, String), and by creating a function called Number, you are occluding this built-in object, which is inadvisable (code that needs to use it will invoke your function instead, which is incompatible and has a different purpose).
Use string:
var minNr = '0000';
It's the start value for the regex test, and you need the four zeroes for that. If it would be a number, then you get only one zero for testing. it would help, if you pad it with leading zeroes.
var minNr = '0000',
maxNr = 10000,
prefix = 7199;
function Nummer(min,max) {
var regex = /^(\d{2})\1$/;
var guld_nr;
for(guld_nr = minNr; guld_nr < maxNr;guld_nr++) {
if(regex.test(guld_nr)) {
document.write(prefix + "" + guld_nr + "<br>");
}
}
}
Nummer(minNr, maxNr);
Numbers don't zero-pad themselves; 0000; // 0
Make a custom zero-pad method for it so you can do zpad(0, 4); // "0000"
function zpad(x, digits) {
var pad = '0';
x = x.toString();
digits -= x.length;
while (digits > 0) {
if (digits & 1) x = pad + x;
pad += pad;
digits >>>= 1;
}
return x;
}
Now adjust Nummer accordingly
function Nummer(min, max, prefix) {
var regex = /^(\d{2})\1$/,
i, str;
prefix = prefix || '';
for(i = min; i < max; ++i) {
str = zpad(i, 4);
if(regex.test(str)) console.log(prefix + str);
}
}
and use
Nummer(minNr, maxNr, '7199');
Side note
Nummer is not constructing an Object, consider camel casing it
You could use arithmetic to do the digit pattern check, and keep the result numerical:
var minNr = 0; // it does not help to put 4 zeroes here.
var maxNr = 10000;
var prefix = 7199;
function Nummer(min,max) {
for (var guld_nr = min; guld_nr < max; guld_nr++) {
if (Math.floor(guld_nr/100) === guld_nr % 100 ) {
$(".resultat").append((prefix * 10000 + guld_nr) + "<br>");
}
}
}
Nummer(minNr, maxNr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="resultat"></div>
The problem with your code is when the lower numbers are tested against the regular expression, they are implicitly converted to string, and do not get prefixed zeroes, so they fail on the regular expression.
Anyway, the code will be more efficient when sticking to numbers instead of strings, so I would suggest working with numbers all the way up to the point of outputting them in the browser.
Even more efficient is this code:
var minNr = 0; // it does not help to put 4 zeroes here.
var maxNr = 10000;
var prefix = 7199;
function Nummer(min,max) {
var test = Math.floor(min/100)*100 + Math.floor(min/100)%100;
var guld_nr = test < min ? test + 101 : test;
for (; guld_nr < max; guld_nr+=101) {
$(".resultat").append((prefix * 10000 + guld_nr) + "<br>");
}
}
Nummer(minNr, maxNr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="resultat"></div>

JavaScript - Formating a long integer [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 8 years ago.
How can I take a JavaScript integer of arbitrary length, such as 1234567890, and format it as a string "1,234,567,890"?
You can use toLocaleString() for the format that you have asked.
var myNum = 1234567890;
var formattedNum = myNum.toLocaleString();
The best way is probably with a regular expression. From How to print a number with commas as thousands separators in JavaScript:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
My solution:
var number = 1234567890;
var str = number + "";
var result = str.split('').map(function (a, i) {
if ((i - str.length) % 3 === 0 && i !== 0) {
return ',' + a;
} else {
return a;
}
}).join('');
See fiddle.

How to trim a string to N chars in Javascript?

How can I, using Javascript, make a function that will trim string passed as argument, to a specified length, also passed as argument. For example:
var string = "this is a string";
var length = 6;
var trimmedString = trimFunction(length, string);
// trimmedString should be:
// "this is"
Anyone got ideas? I've heard something about using substring, but didn't quite understand.
Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.
var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);
Copying Will's comment into an answer, because I found it useful:
var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ?
string.substring(0, length - 3) + "..." :
string;
Thanks Will.
And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)
I suggest to use an extension for code neatness.
Note that extending an internal object prototype could potentially mess with libraries that depend on them.
String.prototype.trimEllip = function (length) {
return this.length > length ? this.substring(0, length) + "..." : this;
}
And use it like:
var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr
From link:
string.substr(start[, length])
let trimString = function (string, length) {
return string.length > length ?
string.substring(0, length) + '...' :
string;
};
Use Case,
let string = 'How to trim a string to N chars in Javascript';
trimString(string, 20);
//How to trim a string...
Prefer String.prototype.slice over the String.prototype.substring method (in substring, for some cases it gives a different result than what you expect).
Trim the string from LEFT to RIGHT:
const str = "123456789";
result = str.slice(0,5); // "12345", extracts first 5 characters
result = str.substring(0,5); // "12345"
startIndex > endIndex:
result = str.slice(5,0); // "", empty string
result = str.substring(5,0); // "12345" , swaps start & end indexes => str.substring(0,5)
Trim the string from RIGHT to LEFT: (-ve start index)
result = str.slice(-3); // "789", extracts last 3 characters
result = str.substring(-3); // "123456789" , -ve becomes 0 => str.substring(0)
result = str.substring(str.length - 3); // "789"
Little late... I had to respond. This is the simplest way.
// JavaScript
function fixedSize_JS(value, size) {
return value.padEnd(size).substring(0, size);
}
// JavaScript (Alt)
var fixedSize_JSAlt = function(value, size) {
return value.padEnd(size).substring(0, size);
}
// Prototype (preferred)
String.prototype.fixedSize = function(size) {
return this.padEnd(size).substring(0, size);
}
// Overloaded Prototype
function fixedSize(value, size) {
return value.fixedSize(size);
}
// usage
console.log('Old school JS -> "' + fixedSize_JS('test (30 characters)', 30) + '"');
console.log('Semi-Old school JS -> "' + fixedSize_JSAlt('test (10 characters)', 10) + '"');
console.log('Prototypes (Preferred) -> "' + 'test (25 characters)'.fixedSize(25) + '"');
console.log('Overloaded Prototype (Legacy support) -> "' + fixedSize('test (15 characters)', 15) + '"');
Step by step.
.padEnd - Guarentees the length of the string
"The padEnd() method pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string. The source for this interactive example is stored in a GitHub repository."
source: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
.substring - limits to the length you need
If you choose to add ellipses, append them to the output.
I gave 4 examples of common JavaScript usages. I highly recommend using the String prototype with Overloading for legacy support. It makes it much easier to implement and change later.
Just another suggestion, removing any trailing white-space
limitStrLength = (text, max_length) => {
if(text.length > max_length - 3){
return text.substring(0, max_length).trimEnd() + "..."
}
else{
return text
}
There are several ways to do achieve this
let description = "your test description your test description your test description";
let finalDesc = shortMe(description, length);
function finalDesc(str, length){
// return str.slice(0,length);
// return str.substr(0, length);
// return str.substring(0, length);
}
You can also modify this function to get in between strings as well.
Here is my solution, which includes trimming white space too.
const trimToN = (text, maxLength, dotCount) => {
let modText = text.trim();
if (modText.length > maxLength) {
modText = text.substring(0, maxLength - dotCount);
modText = modText.padEnd(maxLength, ".");
return modText;
}
return text;
};
trimToN('Javascript', 6, 2) will return "Java.."
I think that you should use this code :-)
// sample string
const param= "Hi you know anybody like pizaa";
// You can change limit parameter(up to you)
const checkTitle = (str, limit = 17) => {
var newTitle = [];
if (param.length >= limit) {
param.split(" ").reduce((acc, cur) => {
if (acc + cur.length <= limit) {
newTitle.push(cur);
}
return acc + cur.length;
}, 0);
return `${newTitle.join(" ")} ...`;
}
return param;
};
console.log(checkTitle(str));
// result : Hi you know anybody ...

Categories