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

对象key的驼峰转下划线 #55

Open
Sunny-117 opened this issue Nov 3, 2022 · 3 comments
Open

对象key的驼峰转下划线 #55

Sunny-117 opened this issue Nov 3, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

实现函数:将对象小驼峰式的属性名转下划线如:userName -> user_name

@bearki99
Copy link

function transform(str) {
  let res = "";
  for (let i = 0; i < str.length; i++) {
    if (str[i] >= "A" && str[i] <= "Z") {
      res += "_" + str[i].toLowerCase();
    } else {
      res += str[i];
    }
  }

  return res;
}
console.log(transform("strAbc"));

@kangkang123269
Copy link

str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();

@veneno-o
Copy link
Contributor

let userName = "userName";
userName = userName.replace(/([a-z])([A-Z])/g, function(text, $1, $2){
    return $1 + "_" + $2.toLowerCase();
})
console.log(userName)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants