最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ToString() and .replace in one line? - Stack Overflow

programmeradmin5浏览0评论

Is it possible to bine 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");

Is it possible to bine 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");
Share Improve this question asked Jan 25, 2016 at 3:17 ConfusedDeerConfusedDeer 3,4158 gold badges46 silver badges77 bronze badges 2
  • 1 Have you actually tried? – PM 77-1 Commented Jan 25, 2016 at 3:21
  • What is myFirstVar value? – Tushar Commented Jan 25, 2016 at 3:25
Add a ment  | 

2 Answers 2

Reset to default 5

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

You can use:

 var mySecondVar = myFirstVar.toString().replace("a","u");
发布评论

评论列表(0)

  1. 暂无评论