[英]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
.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:在哪里:
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.