How to reverse a string using only one variable - javascript

How to reverse string using next conditions:
1) if string isn't parameter of function,
2) if string is place in global scope,
3) use loop like for, while,
4) can add one variable
Note: Can't use method .join, .split, .reverse and so on...
If it possible and not so hard for you make explain your solution, very grateful !
In other words, this is what you got:
let s = 'any string';
let p; // feel free to use at your discretion
// your code here. No further variables, no functions and no built-ins
// should console.log the reversed string
I'm understand that my solution is very close to my desire (conditions), but i can't generate other solution.
function convers(s){ //parameter
var str = "";//empty string for new converted string
for(var i = s.length-1; i >= 0; i--)//loop decremebtation that count from end of string
str+=s[i];//store result and assignments to str
return str;// declare result
}
console.log(convers("abcdef"));
I looked this source:
javascript reverse string algorithm
Is there a faster Reverse String Algorithm for JavaScript? - but it is useless for me, sorry.
I'm sorry if my explanation is not clear enough. Sorry for my English, I'm beginner here :))))

You could use a new variable for the reverted string and use the length property for iterating.
var string = 'abcdef',
reverse = '';
while (reverse.length !== string.length) {
reverse += string[string.length - 1 - reverse.length];
}
string = reverse;
console.log(string);
A bit shorter.
var string = 'abcdef',
reverse = '';
while (reverse.length !== string.length) {
reverse = string[reverse.length] + reverse;
}
string = reverse;
console.log(string);

Please check below condition I hope it will help you
1) if string isn't parameter of function
function convers(s){ //parameter
s = s.toString();
var str = "";//empty string for new converted string
for(var i = s.length-1; i >= 0; i--)//loop decremebtation that count from end of string
str+=s[i];//store result and assignments to str
return str;// declare result
}
console.log(convers(132));
2) if string is place in global scope
function convers(){ //parameter
var str = "";//empty string for new converted string
for(var i = dd.length-1; i >= 0; i--)//loop decremebtation that count from end of string
str+=dd[i];//store result and assignments to str
return str;// declare result
}
var dd ="123";
console.log(convers());
3) can add one variable
function convers(s,dd){ //parameter
var str = "";//empty string for new converted string
for(var i = s.length-1; i >= 0; i--)//loop decremebtation that count from end of string
str+=s[i];//store result and assignments to str
return str +dd;// declare result
}
function CallConvers(){
var dd = "ADD";
console.log(convers("abcdef",dd));
}
CallConvers();

Related

Reshape String, inserting "\n" at every N characters

Using JavaScript functions, I was trying to insert a breakline on a string at every N characters provided by the user.
Just like this: function("blabla", 3) would output "bla\nbla\n".
I searched a lot of answers and ended up with a regex to do that, the only problem is, I need the user's input on the matter, so I need to stuck a variable on this regex.
Here's the code:
function reshapeString(string, num) {
var regex = new RegExp("/(.{" + num + "})/g");
return string.replace(regex,"$1\n");
}
reshapeString("blablabla", 3);
This is currently not working. I tried to escape the '/' characters, but I'm screwing up at some point and I don't know where.
What am I missing? Is there any other way to solve the problem of reshaping this string?
You need a string for the regexp constructor, without /, and you can omit the group by using $& for the found string.
function reshapeString(string, num) {
var regex = new RegExp(".{" + num + "}", "g");
return string.replace(regex,"$&\n");
}
console.log(reshapeString("blablabla", 3));
How about a one-liner?
const reshapeString = (str,N) => str.split('').reduce((o,c,i) => o+(!i || i%N?'':'\n')+c, '')
Explanation:
So first thing we do is split the string into a character array
Now we use a reduce() statement to go through each element and reduce to a single value (ie. the final string you're looking for!)
Now i%N should give a non-zero (ie. a truthy value) when the index is not a multiple of N, so we just add the current character to out accumulator variable o.
If i%N is in fact 0 (then it's falsey in value), and we append:
o (the string so far) +
\n (the appended character at the N'th interval)
c (the current character)
Note: We also have a !i check, that's for ignoring the first char since, that may be considered un-intended behavior
Benchmarking
Regex construction and replace also requires string re-construction and creating an FSA to follow. Which for strings smaller than 1000 should be slower
Test:
(_ => {
const reshapeString_AP = (str,N) => str.split('').reduce((o,c,i) => o+(!i || i%N?'':'\n')+c, '')
function reshapeString_Nina(string, num) {
var regex = new RegExp(".{" + num + "}", "g");
return string.replace(regex,"$&\n");
}
const payload = 'a'.repeat(100)
console.time('AP');
reshapeString_AP(payload, 4)
console.timeEnd('AP');
console.time('Nina');
reshapeString_Nina(payload, 4)
console.timeEnd('Nina');
})()
Results (3 runs):
AP: 0.080078125ms
Nina: 0.13916015625ms
---
AP: 0.057861328125ms
Nina: 0.119140625ms
---
AP: 0.070068359375ms
Nina: 0.116943359375ms
public static String reshape(int n, String str){
StringBuilder sb = new StringBuilder();
char[] c = str.replaceAll(" " , "").toCharArray();
int count =0;
for (int i = 0; i < c.length; i++) {
if(count != n){
sb.append(c[i]);
count++;
}else {
count = 1;
sb.append("\n").append(c[i]);
}
}
return sb.toString();
}
Strings are immutable so whatever you do you have to create a new string. It's best to start creating it in the first place.
var newLineForEach = (n,s) => s && `${s.slice(0,n)}\n${newLineForEach(n,s.slice(n))}`,
result = newLineForEach(3,"blablabla");
console.log(result);
So my tests show that this is by far the fastest. 100K iterations resulted Nina's 1260msec, AP's 103msec and Redu's 33msec. The accepted answer is very inefficient.

Passing the value of a sub-array into CharCodeAt in JavaScript

Essentially I am working on this coding challenge on FreeCodeCamp. The start of the challenge mentions this to start with...
A common modern use is the ROT13 cipher, where the values of the
letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on.
Write a function which takes a ROT13 encoded string as input and
returns a decoded string.
So far I have passed the string to an array, with each part of the string in its own array (a sub-array). From there I figure I would use a loop to go through each character in the string (in each sub-array) and pass the CharCodeAt method to each one.
My problem lies with passing each individual character to go through CharCodeAt.
This is a part of the total function which follows below:
To me this makes sense, as I 'am passing each sub-array value in a variable
var foo = container[i][k];
// var output = container.map(function mapHandler(){foo.charCodeAt(k)});
function rot13(str){
var container, j = 0;
while(j <= str.length - 1){
container = str.split(' ');
j++;
}
for(var i = 0; i < container.length; i++){
for(var k = 0; k < container[i].length; k++){
var foo = container[i][k];
var map = Array.prototype.map;
var output = map.call(foo, function(x){ return x.charCodeAt(k);});
// var output = container.map(function mapHandler(){foo.charCodeAt(k)});
// output.charCodeAt(k);
}
}
return output;
}
rot13("SERR PBQR PNZC") should decode to "FREE CODE CAMP"
Could anyone just help get to this point? I don't want the whole solution!
Thanks in advance!
You can turn a string into array of single letters by splitting it with an empty string:
var arr = str.split("")
Then you can use for example .map() to change each letter into decoded one:
var decoded = arr.map(x=> {
// decode x
})

Javascript - Find an replace a part of a string with value from an array

I have an string, but at certain points in the string it has dynamic values.
I want to find those points in the string and replace them with values from an array.
Let's say I have:
var array = ['string', 'value'];
var string = 'This is a {1}, and this is a {2}.';
Now I need to figure out a way to replace {1}, with the value of the first index in the array and replace {2} with the value of the second index of the array.
So the string would like this:
This is a string, and this is a value.
This seems so simple, but I am breaking my head on this. I can't find a way to do this easily.
You can use replace with a regular expression and a function:
string.replace(/{(\d+)}/g, function(match, n) {
return array[n-1];
});
You can also check n < 1 || n > array.length to provide a fallback value in case the number is out of bounds.
Alternatively, the new ES6 way is using tagged template strings
function tag(strings, ...values) {
var parts = [];
for(var i=0; i<strings.length; ++i)
parts.push(strings[i], array[values[i]-1]);
return parts.join('');
}
tag`This is a ${1}, and this is a ${2}.`
like this
string.replace(/\{(\d+)\}/g, function(m, n){
return array[n-1]
})
You can use Array.prototype.reduce:
var StringHelper = {
format: function(format, args) {
return args.reduce(function(result, currentReplace, currentReplaceIndex) {
result = result.replace("{" + (currentReplaceIndex + 1) + "}", args[currentReplaceIndex]);
return result;
}, format);
}
};
var sourceString = "My name is {1} and I'm {2} years old";
var replaceItems = ["Matías", "31"];
var parsedString = StringHelper.format(sourceString, replaceItems);
alert(parsedString);
It's a good alternative to regular expressions, and I'm not absolutely sure if I did a jsPerf test in the right way, but it shows that this approach outperforms the regular expression one.

Any javascript string function?

Some outside code is giving me a string value like..
null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,
now i have to save this value to the data base but putting 0 in place of null in javascript. Is there any javascript string releated function to do this conversion?
You can simply use the replace function over and over again until all instances are replaced, but make sure that all your string will ever contain is the character sequence null or a number (and obviously the delimiting comma):
var str = "null,402,2912,null"
var index = str.indexOf("null");
while(index != -1) {
str = str.replace("null", "0");
index = str.indexOf("null");
}
You need to run a for loop because the function String.replace(search, rplc) will replace only the first instance of search with rplc. So we use the indexOf method to check, in each iteration, if the required term exists or not. Another alternative (and in my opinion, a better alternative would be:
var str = "null,402,2912,null"
var parts = str.split(",");
var data = []
for(var i=0; i<parts.length; i++) {
data[data.length] = parts[i]=="null"?0:parseInt(parts[i]);
}
Basically, what we are doing is that since you will anyways be converting this to an array of numbers (I presume, and sort of hope), we first split it into individual elements and then inspect each element to see if it is null and make the conversion accordingly.
This should answer your needs:
var str = 'null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390';
str.split(",").map(function (n) { var num = Number(n); return isNaN(num) ? 0 : num; });
The simplest solution is:
var inputString = new String("null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,");
var outputString = inputString.replace("null", "0");
What I understood from your question is:
You want to replace null with 0 in a string.
You may use
string = "null,402,2912,2909,2910,2913,2911,2914,2915,2388,2389,2390,"
string.replace(/null/g,0)
Hope it helps.

Regex replace string which is not float

I have a string, where I need to parse it as a float, but first I need to replace it, if it is not a number (an integer or a float), so I am trying to create an regular expression to do it
My tries results in NaN
One of my best tries is
var $replace = $text.replace(/^[^d.]*/, '');
var $float = parseFloat($replace);
Can anybody tell me, what I am doing wrong?
If you really want to replace everything thats not a digit, then try this:
var $replace = $text.replace(/[^\d.]/g, '');
var $float = parseFloat($replace);
This will replace a string of "123a3d2" with a string of "12332".
It looks like you want to strip "non-numeric" characters from the beginning of the string before converting it to float. A naive approach would be:
var s = input.replace(/^[^\d.]+/, '');
var n = parseFloat(s);
This works for inputs like "foo123" but will fail on "foo.bar.123". To parse this we need a more sophisticated regexp:
var s = input.replace(/^(.(?!\d)|\D)+/, '');
var n = parseFloat(s);
Another method is to strip the input char by char until we find a valid float:
function findValidFloat(str) {
for (var i = 0; i < str.length; i++) {
var f = parseFloat(str.substr(i))
if (!isNaN(f))
return f;
}
return NaN;
}
if (! isNaN($text))
$float = parseFloat($text);
else
$float = 0; // or whatever

Categories

Resources