我有一个字符串例如:
var string = 'This is a test sentence. Switch the characters. i .';
我希望将字母“i”的每次出现的位置切换到跟随它的字符,除非后面的字符是't'或非字符如'spaces'或'换行符'。所以结果输出应该是:
Thsi si a test sentence. Switch the characters. i . // switches 's' but not 't' and 'space'
使用正则表达式可以完成这样的任务吗?我正在使用的字符是unicode字符。 '我'只是一个例子。这意味着匹配所有角色并不是一个好主意。可能是 不 表达式?我尝试了一些循环替换,但这些不优雅(或高效)。有什么想法吗?
答案 0 :(得分:4)
您可以使用该格式的正则表达式替换:
var string = 'This is a test sentence. Switch the characters. i .';
var result = string.replace(/(i)(?![t\s])(.)/g, "$2$1");
(i)
将i
匹配并捕获到变量$1
中。
(?![t\s])
会阻止t
和空格的匹配。
(.)
匹配并将任何其他字符捕获到变量$2
。
答案 1 :(得分:1)
您可以使用正则表达式:/(i)([^t\W])/gi
代码:
var string = 'This is a test sentence. Switch the characters. i .';
string.replace(/(i)([^t\W])/gi,"$2$1");
<强> DEMO 强>
说明: