是否有一种干净的方法来反转与 JavaScript 中特定正则表达式匹配的子字符串?
对于像 /[a-g]+/
这样的正则表达式和像 "sgsadebfdzgbd"
这样的字符串来获取 "sgsdfbedadbg"
只有哪里子字符串 "adebfd"
和 "gbd"
就地反转了。
最佳答案
使用自定义函数进行replace
:
your_string.replace(/([a-g]+)/g, function(all, word) {
return word.split("").reverse().join("");
});
例子:
> "sgsadebfdzgbd".replace(/([a-g]+)/g, function(all, word) {
return word.split("").reverse().join("");
});
"sgsdfbedazdbg"
您也可以使用这个更短但(在我看来)不太清晰的版本:
your_string.replace(/[a-g]+/g, function(word) {
return word.split("").reverse().join("");
});
关于javascript - 翻转匹配子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17630854/