JavaScript字符串排序:将0{#3#}1{#1#}2{#2#} 3{#4#}改成0{#1#}1{#2#}2{#3#}3{#4#}
//u003ccode//u003ejs//u003c///code//u003e//n//u003ccode//u003ejs//nlet str //u003d ///'0//u003c//#3//#//u003e1//u003c//#1//#//u003e2//u003c//#2//#//u003e 3//u003c//#4//#//u003e///'//u003b//n//n//u002f//u002f 提取数字和原始顺序的映射关系//nlet map //u003d //{}//u003b//nstr.replace//(///(//d+//)//u003c//#//(//d+//)//#//u003e///g, function//(match, p1, p2//)// {//n map///[p2///] //u003d p1//u003b//n//}//)//u003b//n//n//u002f//u002f 根据映射关系重新排序//nlet newStr //u003d str.replace//(//d+//u003c//#//d+//#//u003e///g, function//(match//)// {//n let index //u003d match.match//(//d+///)///[0///]//u003b//n return map///[index///] + match.slice//(index.length//)//u003b//n//}//)//u003b//n//nconsole.log//(newStr//)//u003b //u002f//u002f 输出: 0//u003c//#1//#//u003e1//u003c//#2//#//u003e2//u003c//#3//#//u003e 3//u003c//#4//#//u003e//n//u003c///code//u003e//n//n这段代码首先通过正则表达式提取出数字和原始顺序的映射关系,然后根据映射关系重新排序字符串中的部分内容。最终得到的newStr就是重新排序后的字符串。
原文地址: https://www.cveoy.top/t/topic/pO9C 著作权归作者所有。请勿转载和采集!