ToString() and .replace in one line?

Is it possible to combine these two lines of code into one?

Meaning, can we do a ToString() and .replace() in one line?

var mySecondVar = myFirstVar.ToString()
mySecondVar = mySecondVar.replace("a","u");
2

2 Answers

Yes, you can chain the methods.

myFirstVar.toString().replace('a', 'u')

Note:

  1. ToString should be toString
  2. String#replace will only replace the first occurrence of the string. To replace all occurrences use replace with RegEx
1

You can use:

 var mySecondVar = myFirstVar.toString().replace("a","u");

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like