javascript中的字符串首字母转大写,字符串反转
作者:互联网
// 字符串首字母转大写,后面字母小写
/**
* 方法一:js字符串切割
* @param {*} str
*/
function firstToUpper1(str) {
return str.trim().toLowerCase().replace(str[0], str[0].toUpperCase());
}
/**
* 方法二:js正则
* @param {*} str
*/
function firstToUpper2(str){
return str.replace(/\b(\w)(\w*)/g, function($0, $1, $2) {
return $1.toUpperCase() + $2.toLowerCase();
});
}
/**
* 方法三:js正则
* @param {*} str
*/
function firstToUpper3(str){
return str.toLowerCase().replace(/( |^)[a-z]/g,(L)=>L.toUpperCase());
}
/**
* 方法三:css
*/
// text-transform: capitalize;
let str='hELLO'
console.log(firstToUpper1(str));
console.log(firstToUpper2(str));
console.log(firstToUpper3(str));
// 字符串反转
/**
* 方法一:js字符串反转
* unshift()
*/
var name = "My city is WH";
var nameArr = name.split('');
var result=[];
var resultStr = '';
for (var i = 0, l = nameArr.length; i < l; i++) {
result.unshift(nameArr[i]);
}
for (var i = 0, l = result.length; i < l; i++) {
resultStr += result[i];
}
console.log(resultStr); // HW si ytic yM
/**
* 方法二:js字符串反转
* reverse(),join()
*/
var name = "My city is WH";
var resultStr = name.split('').reverse().join('');
console.log(resultStr); // HW si ytic yM
/**
* 方法三:js字符串反转
* charAt()
*/
var name = "My city is WuHan";
var nameArr = name.split('');
var resultStr = '';
for (var i = nameArr.length-1; i >= 0; i--) {
resultStr += name.charAt(i);
}
console.log(resultStr); // naHuW si ytic yM
标签:console,resultStr,javascript,var,首字母,str,字符串,js,name 来源: https://blog.csdn.net/qq_59717525/article/details/121216648