javascript在字符串中交换字符 [英] javascript swap characters in string

查看:163
本文介绍了javascript在字符串中交换字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串,如abcabcabc,我想要'a'和'b'的位置,以便我最终得到 bacbacbac。对此最优雅的解决方案是什么? (为了这个问题,我特此将'优雅'定义为快速和可读。)

Let's say I have a string like "abcabcabc" and i want the positions of 'a's and 'b's swaped so that I end up with "bacbacbac". What is the most elegant solution for this? (For the sake of this question I hereby define 'elegant' as fast and readable.)

我想出了

"abcabcabc".replace( /[ab]/g, function( c ){ return { 'a': 'b', 'b': 'a' }[ c ] } )

我既不认为快也不可读。但现在我想知道是否有更好的方法呢?

which I neither regard fast nor readable. But now I wonder if there is a better way doing it?

编辑:角色可以在任何位置。所以答案应该适用于xyza123buvwa456(当时也是xyzb123auvwb456。

The characters can be at any position. So the answer should hold for "xyza123buvwa456" (would be then "xyzb123auvwb456", too.

EDIT2:swap似乎是错误的词。替换所有的使用b和所有b都有一段时间都是单个字符。

"swap" seems to be the wrong word. Replace all of a with b and all of b with a while both are single characters.

我投入其他几个:

"abcabcabc".replace( 'a', '_' ).replace( 'b','a' ).replace( '_', 'b' )

"abcabcabc".replace( /[ab]/g, function( c ){ return "ba".charAt( c.charCodeAt()-'a'.charCodeAt() ); } )

"abcabcabc".replace( /[ab]/g, function( c ){ return "ab".charAt( "ba".indexOf( c ) ) } )

我最终使用了Mark C.的修改版本。答案:

I ended up using a modified version of Mark C.'s Answer:

"abcabcabc".replace( /[ab]/g, c => c == 'a' ? 'b' : 'a' )


推荐答案

试试这个:

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

例如:

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

这篇关于javascript在字符串中交换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆