Why is my str.replace line not working? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I'm making a function that takes a string, cuts the first half (leaving middle character if odd string.length) and adds first half to end of string.
For some reason my function only partlyworks: it adds the substr to the end but doesn't cut it from the start. I tried .replace but not working.
What am I doing wrong? And/or is there a better way?

replace returns a new string with the replacement, it doesn't modify the string you call it on.
Additionally, as Pointy pointed out, you've passed the literal string 'substr' in, rather than passing in the variable substr.
So:
s = s.replace(substr, '');

a friend just gave another way to write a function that does what I wanted mine to do . I'm an amoeba and you're all wizards
function doit(s){
split = s.length /2;
if(split % 2 !== 0) { split = split-1; }
var partOne = s.slice(0, split);
var partTwo = s.slice(split + 1, s.length);
return partTwo + partOne;
}
alert(doit('123456789qwertyuio'));

Related

How can I change a string to be all lowecase and push something to the end? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
So I have a function that will be called with a 1 word string.
Test("ABCD")
my code:
function Test(x)
var str=""
str.push($)
x.toLowerCase()
return str
//So I want the output to change the "ABCD" into "abcd$"
You are accepting the argument x in the function and running toLowerCase on it. The output is not having any value from the input.
Also there is no push method defined for string. It can be String.concat. Even that is not needed, you could make use of arithematic + itsel for concatenation or string leterals.
Just lowercase the input append a $ symbol. Its done!!
Im making use of .toString() method aswell. To ensure code is not breaking for other input types
It should be
function Test(x) {
return x.toString().toLowerCase() + '$'
}
console.log(Test("ABCD"));
Or Simply.
Test = (x) => `${ x.toString().toLowerCase() }$`;
console.log(Test("ABCD"));
This is just an example, please change the text which you want to add at end as you wish.
I passed the string in function through console.log but you can call the function as you wish without console.log.
function capFirst(str) {
return str.toLowerCase().concat('', '$');
}
console.log(capFirst('ABCD'));

Javascript: Regex for "DD/MM/YY HH:SS" not succeeding [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have the following datetime string: 09/07/2020 02:00
I need to check the format of the string before apply Date.parse() to ensure that it's in the correct format. I've developed a regular expression for the string however it doesn't appear to work in Javascript. I've tested it and it works in regex tester but not in js. Example (regex101) here
REGEX
String
09/07/2020 02:00
Expression
^([1-9]|([012][0-9])|(3[01]))(\/)([0]{0,1}[1-9]|1[012])(\/)\d\d\d\d (20|21|22|23|[0-1]?\d):[0-5]?\d$
function clean_inputdatetime(datetime) {
var cleaned_datetime = null
var datetime_regex_cond = RegExp('/^([1-9]|([012][0-9])|(3[01]))(\/)([0]{0,1}[1-9]|1[012])(\/)\d\d\d\d (20|21|22|23|[0-1]?\d):[0-5]?\d$/', 'g')
var regex_success = datetime_regex_cond.test(datetime)
if (regex_success) {
var cleaned_datetime = Date.parse(datetime)
}
return [regex_success, cleaned_datetime]
}
console.log(
clean_inputdatetime("09/07/2020 02:00")
)
Note regex_success returns false for above.
When using RegExp you need to remove the enclosing slashes - otherwise they will be included in the regex itself. Also you need to correctly escape the string:
const datetime_regex_cond = new RegExp('^([1-9]|([012][0-9])|(3[01]))(\\/)([0]{0,1}[1-9]|1[012])(\\/)\\d\\d\\d\\d (20|21|22|23|[0-1]?\\d):[0-5]?\\d$','g')
Or simply do:
const datetime_regex_cond = /^([1-9]|([012][0-9])|(3[01]))(\/)([0]{0,1}[1-9]|1[012])(\/)\d\d\d\d (20|21|22|23|[0-1]?\d):[0-5]?\d$/g;

Simple math coming out wrong [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I've made a super simple script to pop out some hourly rates from a pool of tips. Thing is, this one specific result always comes out wrong. What the heck is going on?
var tips = prompt('Enter final tips after payouts and cleaning');
//Hours worked for both positions
var tendHrsFirst = 11;
var tendHrsSecond = 10;
//Hourly Rate
var barThourly = ((tips/(tendHrsFirst+++tendHrsSecond)));
//This result here always comes out as if tendHrsFirst is 12 and not 11.
var barToneTotal = (tendHrsFirst * barThourly);
//This result is always correct
var barTtwoTotal = (tendHrsSecond * barThourly);
You are incrementing with tendHrsFirst++, so it actually is 12.
I guess those are actually two commands.
tendHrsFirst++ increments tendHrsFrist by 1. Afterwards, you add both numbers. Not sure why you think that's a good idea. Cleaning up your code should help avoiding such mistakes.
here
var barThourly = ((tips/(tendHrsFirst+++tendHrsSecond)));
you are using +++ that means postfix increase of tendHrsFirst and added to tendHrsSecond
or maybe
prefix increase of tendHrsSecond added to tendHrsFirst

Why is this Javascript failing to find the right index? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I was testing my answer to another SO question and came across this weird behavior, for the life of me I don't know what is up.
Code:
function translateLetter(input) {
const untranslated = "abcdefghijklmnopqrstuvwxyz";
const translated = "zyxwvutsrqponmlkjihgfedcba";
var i = untranslated.indexOf(input);
console.log(i);
return translated.substring(i,1);
}
console.log(translateLetter("a"));
console.log(translateLetter("b"));
console.log(translateLetter("c"));
Expected output:
0
z
1
y
2
x
Actual output:
0
z
1
<--- WTH?
2
y <--- WTF?
Code on JSFiddle
If speed is important, I'd use an object to do your lookup.
eg.
var translateLetter= {a:'z',b:'y'... etc }
and then you can simply do ->
console.log(translateLetter['a'])
Use .substr() for a length. .substring() takes a position.
The first empty space is a null because you have passed "b" in the function on which indexOf function returned 1 which is then set to variable "i" and i is then used in substring function and substring fuction return the value which is in the middle including the first and excluding the last index of the values given so substring got (1,1) and 1,1 are pointing the same index so it returned null.
same for the second.
substring(Begin index inclusive,last index exclusive);

Getting the last 2 characters of a dynamic string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I need your help.
One thing that's always going to be known in my function is that my string will always have a -2 at the end.
ie.
var x = filenumber-2
I'd like to use an if statement to check if the string: -2 is attached to the string. If it is just return true.
Since the filenumber value will be a variety of different combinations its length will always need to be accounted for. But as for the the -2 at the end, it is a given.
Simple regex-based solution:
if (/-2$/.test(filenumber)) return true;
Using either the String slice() or substr() methods:
if (filenumber.slice(-2) =="-2") return true;
if (filenumber.substr(-2)=="-2") return true;
The -2 in the method call means "start 2 characters before the end of the string".
if(x.slice(-2) == "-2") return true;
Will this suffice?
Use the negative operator of the slice method. It starts counting backwards from the end of the string, so it doesn't matter how long it is.
if(x.slice(-2) == "-2"){
return true;
}
Or if you really want you could use its length and count from the start
if(x.slice(x.length - 2) == "-2"){
return true;
}

Categories