Javascript swap characters in string

前端 未结 5 1307
失恋的感觉
失恋的感觉 2021-01-15 05:04

Let\'s say I have a string like "abcabcabc" and I want the positions of \'a\'s and \'b\'s swapped so that I end up with "bacbacbac"

5条回答
  •  逝去的感伤
    2021-01-15 05:51

    You can swap them (if they're always adjacent) by using a split/join combo:

    console.log("abcabcabc".split("ab").join("ba"))

    And in keeping with the split/join method, here's a way to swap them as individual characters (although it becomes significantly less readable):

    console.log("aabbccaabbcc".split("a").map(s => s.split("b").join("a")).join("b"));

提交回复
热议问题