Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

字符串取反 #41

Open
bibi7 opened this issue Oct 30, 2019 · 0 comments
Open

字符串取反 #41

bibi7 opened this issue Oct 30, 2019 · 0 comments

Comments

@bibi7
Copy link
Owner

bibi7 commented Oct 30, 2019

给定任意字符串,进行字符串大小写取反

还是说说第一时间想到的吧,正则匹配每一个字符进行比较后取反:

const transformCase = (str) => str.replace(/[a-zA-Z]/g, item => {
  return item === item.toUpperCase() ? item.toLowerCase() : item.toUpperCase()
})

小写字符的ascii码大于大写字符的ascii,并且大写Z的ascii为90,那么可以换种思路:

const transformCase = (str) => {
  const array = str.split('').map(item => item.codePointAt(0) <= 90 ? item.toLowerCase() : item.toUpperCase())
  return array.join('')
}

正则match?

const transformCase = (str) => {
  return str.replace(/[a-zA-Z]/g, match => /[a-z]/.test(match) ? match.toUpperCase() : match.toLowerCase())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant