题解 | #字符串排序# JS Node一楼加注释便于理解
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.on("line", function (line) { // 字符串切片,同split('') let res = Array.from(line); // 过滤其他字符,将字母原地排序 let lineCopy = Array.from(line.replace(/[^a-z]/gim, "")).sort((a, b) => { let x = a.toLowerCase(); let y = b.toLowerCase(); return x < y ? -1 : x > y ? 1 : 0; }); // 将排序好的字母替换原字母,字符则不替换 res.forEach((word, index) => { if (/[a-z]/gim.test(word)) { res[index] = lineCopy[0]; lineCopy.shift(); } }); console.log(res.join("")); }); /* 关于正则的补充 */ // g(全局搜索出现的所有 pattern) // i(忽略大小写) // m(多行搜索) // ^匹配除了 [...] 中字符的所有字符,例如 [^aeiou] 匹配字符串 "google runoob taobao" 中除了 e o u a 字母的所有字母。