使用JavaScript代码按大写字母拆分字符串

javascript编写示例代码,为字母表中的每个大写字母拆分一个字符串。可以通过对“split”方法使用正则表达式。既然是“split”,那么拆分的结果就是一个数组。

按大写拆分字符串

可以通过在“split”中使用正则表达式“(?=[AZ])”来按大写拆分字符串。结果以数组形式返回。

const str = 'HelloWorld!!';

const result = str.split(/(?=[A-Z])/);

console.log(result);
// ['Hello', 'World!!']

大写字母在被发现时被拆分,因此当发现大写字母“W”时,下面的代码将被拆分。

const str = 'helloWorld!!';

const result = str.split(/(?=[A-Z])/).map(v => v.trim());

console.log(result);
// ['hello', 'World!!']

使用JavaScript代码按大写字母拆分字符串

如果有空白,指定“map”去掉,用“trim”去掉空白。

* "trim" 删除前导和尾随空格。

const str = 'Hello World!!';

const result = str.split(/(?=[A-Z])/).map(v => v.trim());

console.log(result);
// ['Hello', 'World!!']

如果不存在大写字母,则生成一个单元素数组。

const str = 'helloworld!!';

const result = str.split(/(?=[A-Z])/).map(v => v.trim());

console.log(result);
// ['helloworld!!']


最后编辑于:2023/03/11作者: 烽烟无限