Skip to content

Instantly share code, notes, and snippets.

@Jancat
Created May 19, 2018 07:54
Show Gist options
  • Save Jancat/c33431da7f66f291c58e4c141c0485ed to your computer and use it in GitHub Desktop.
Save Jancat/c33431da7f66f291c58e4c141c0485ed to your computer and use it in GitHub Desktop.
前端面试题
/*
题目:找出字符串中第一个出现一次的字符
Sample: 'google' => 'l'
*/
// 解法一:使用正则匹配字符
function find(str) {
for (const i of str) {
const char = str[i]
const reg = new RegExp(char, 'g')
if (str.match(reg).length === 1) {
return char
}
}
}
// 解法二:使用 indexOf/lastIndexOf
/*
题目:将1234567 变成 1,234,567,即千分位标注
*/
// 解法:使用正则零宽断言
function exchange(num) {
num += '' //转成字符串
if (num.length <= 3) {
return num
}
// 第一个逗号后面数字的个数是3的倍数:/(\d{3})+$/
// 第一个逗号前最多可以有 1~3 个数字,正则:/\d{1,3}/
return num.replace(/\d{1,3}(?=(\d{3})+$)/g, v => v + ',')
}
console.log(exchange(1234567))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment