Javascript swap characters in string

前端 未结 5 1344
失恋的感觉
失恋的感觉 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' }))

提交回复
热议问题