Javascript swap characters in string

前端 未结 5 1305
失恋的感觉
失恋的感觉 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:45

    Try this :

    str.replace(/[ab]/g, function($1) { return $1 === 'a' ? 'b' : 'a' })
    

    example:

    console.log("abcabcabc".replace(/[ab]/g, function($1) { return $1 === 'a' ? 'b' : 'a' }))

    0 讨论(0)
  • 2021-01-15 05:45

    replace function accepts a string as the second parameter.

    "abcabcabc".replace( /ab/g, "ba")

    0 讨论(0)
  • 2021-01-15 05:45

    I use this method when I need to swap long list of characters\words\strings!

    The method also prevents strings already replaced to be replaced again, Example:

    String = "AAABBBCCC BBB"
    
    Replace "AAABBBCCC" with "BBB", then, "BBB" with "DDD"
    
    Final String = "BBB DDD"
    

    Note that, only "BBB" from the original string is replaced to "DDD"! The "BBB" replaced from "AAABBBCCC" is not re-replaced to "DDD"!

    0 讨论(0)
  • 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"));

    0 讨论(0)
  • 2021-01-15 05:51

    Use a direct replace using Regex:

    var result = "abcabcabc".replace( /ab/g, "ba");
    console.log(result);

    0 讨论(0)
提交回复
热议问题