Split the string according to special characters, convert the first letter to uppercase, and finally save it as an array

Requirement 1:

According to  the space, &, %, /, _, -, (,)   special characters, split the string, convert the first letter to uppercase, and finally save it as an array

plan:

let str = 'new year%help)help';
let regex = /[ &%/_\-(]/; // 使用正则表达式匹配特殊字符空格、&、%、/、_、-、(

let result = str.split(regex).map(word => {
  return word.charAt(0).toUpperCase() + word.slice(1);
});

console.log(result); // 输出分割后的数组,首字母大写

operation result:

[ 'New', 'Year', 'Help', 'Help' ]

Requirement 2:

Convert the first letter after  &, space, %, /, _, -, (,), and special characters to uppercase

let str = 'aaa%bbb&ccc-ddd_eee(fff)ggg hhh';

// 定义正则表达式,匹配 &、空格、%、/、_、-、(、)、特殊字符
let regex = /([& %/_\-()].)/g;

// 使用正则表达式进行替换,将特殊字符后的第一个字母转为大写
let modifiedStr = str.replace(regex, (match) => {
  // 将匹配到的特殊字符后的第一个字母转为大写
  return match.charAt(0) + match.charAt(1).toUpperCase();
});

console.log(modifiedStr); // 输出转换后的字符串

operation result:

aaa%Bbb&Ccc-Ddd_Eee(Fff)Ggg Hhh

Guess you like

Origin blog.csdn.net/qq_38543537/article/details/131848211