0

Hi I am new to javascript I am trying to create a function that I wanted to call if the string contains (-) will return a string value of "00" but if not will remain the same value. I will really appreciate any help or advice thank you.

example
val1= -01
expected output is =00


val2= 03
expected output:03

Code but not working

I used it like

myFunction(val1);

but this still return same value even string contains this -

function myFunction(myFunction) {

  var n = myFunction.includes("-");
  if (n =="true"){
      return "00:00";
  }else{
      return myFunction;
  }

6 Answers 6

2

It looks like you're checking if the result of calling includes is equal to the string "true", which won't be the case. Simply replacing your if statement with if(n) should do the trick.

Sign up to request clarification or add additional context in comments.

Comments

0

Use Array.prototype.includes() as below:

var val1= '-01';
var val2= '03';

function myFunction(s){
    return s.includes('-') ? '00' : s;
}

console.log(myFunction(val1));
console.log(myFunction(val2));

Comments

0

There are several problems here.

Try this:

function myFunction(myString) {

  if (myString.includes("-")) {
      return "00:00";
  }else{
      return myString;
  }
  1. Use different names for the function ("myFunction") and the function parameter ("myString").

  2. Use the keyword "true", instead of the string "true". Or even better, just use a boolean expression.

Comments

0

Make sure you have proper names for your functions and variables. Further, boolean checks can be simplified directly. Try this

function myFunction(str) {
   if (str.includes("-")) {
     return "00";
   } else {
     return str;
   }
}

An other way would be to use the ternary operator.

function myFunction(str) {
    return str.includes("-") ? "00" : str
}

Comments

0
function myFunction(word) {

  if (word.includes("-")) {
    return "00";
  }

  else {
    return word;
  }
}

console.log(myFunction("-01"));
console.log(myFunction("02"));

Don't use myFunction as both the name of a function and its argument. It's a Bad Idea.

1 Comment

You suggest to not use myFunction as the name for the function and the argument, but you do not explain why the code really failing. Because the naming might be a bad idea but does not explain why it is failing.
-1
function mycontain(s) {
  // check if desired token exists then return special or original
  return s.includes('-') ? '00' : s
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.