简体   繁体   English

如何在 ES6/React 中将小写和下划线转换为正确的大小写和空格

[英]How do I convert lowercase and underscores to proper case and spaces in ES6/React

How do I convert strings with underscores into spaces and converting it to proper case?如何将带下划线的字符串转换为空格并将其转换为正确的大小写?

CODE代码

 const string = sample_orders

 console.log(string.replace(/_/g, ' '))

Expected Output预期产出

Sample Orders

This function should do the job :这个功能应该做的工作:

function humanize(str) {
  var i, frags = str.split('_');
  for (i=0; i<frags.length; i++) {
    frags[i] = frags[i].charAt(0).toUpperCase() + frags[i].slice(1);
  }
  return frags.join(' ');
}


humanize('sample_orders');
// > Sample Orders

JSFiddle JSFiddle

.replace replace only the first occurrence of the target input. .replace只替换第一次出现的目标输入。 In order to replace all the occurrences, use .replaceAll .为了替换所有出现的,使用.replaceAll

 var string = 'sample_orders'

 string = string.replaceAll('_', ' ')

Further converting it to the proper case could be accomplished through regEx可以通过regEx将其进一步转换为正确的大小写

string = string.replace(/(^\w|\s\w)/g, firstCharOfWord => firstCharOfWord.toUpperCase());

Where:在哪里:

  • ^\\w : First char of the string ^\\w : 字符串的第一个字符
  • | | : or : 或者
  • \\s\\w : First char after whitespace \\s\\w :空格后的第一个字符
  • g : global scope(Match all occurrences) g : 全局作用域(匹配所有出现的)
  • The second argument is a function that accepts the first character of each word computed using the regular expression and converts it to an upper case. 第二个参数是一个函数,它接受使用正则表达式计算的每个单词的第一个字符并将其转换为大写。 Binding the above logic into a function: 将上述逻辑绑定到一个函数中:
     function formatString(string){ return string.replaceAll('_', ' ').replaceAll(/(^\\w|\\s\\w)/g, firstCharOfWord => firstCharOfWord.toUpperCase()); } let formattedString = formatString('sample_orders') console.log(formattedString) //Sample Orders

    Caveat : You might encounter an error saying .replaceAll is not a function if you are running on an older browser or runtime environment.警告:如果您在较旧的浏览器或运行时环境中运行,您可能会遇到错误,指出.replaceAll不是函数。 The .replaceAll method was added in ES2021/ES12. .replaceAll方法是在 ES2021/ES12 中添加的。 The best workaround to run such functionalities on older versions of JS is to provide native support to older versions that do not support newly added methods or features ( .replaceAll ) in this case.在旧版本的 JS 上运行此类功能的最佳解决方法是在这种情况下为不支持新添加的方法或功能 ( .replaceAll ) 的旧版本提供本机支持。

     function formatString(string){ return string.replace(/_/g, ' ').replace(/(^\\w|\\s\\w)/g, firstCharOfWord => firstCharOfWord.toUpperCase()); } let formattedString = formatString('sample_orders') console.log(formattedString) //Sample Orders

    Note that we're using the replace method with regular expressions on a global scope.请注意,我们在全局范围内使用带有正则表达式的replace方法。 This could also be used at instances where the strings might not contain underscores.这也可以用于字符串可能不包含下划线的情况。

    声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM