获取每个单词的第一个字母前面有空格或句点



当前面有space.时,我需要取字符串中每个单词的第一个字母

示例1:Hello World I'm a web.dev from.japan.com cool

所需解决方案1:HWIAW.DF.J.CC

示例2:Hello World This is awesome

所需解决方案2:HWTIA

编辑:(我不是很清楚(

我所能想到的就是:

const sentence = "Hello World I'm a web.dev from.japan.com cool";
sentence.split(/[s.]+/).map((n) => n[0]).join("").toUpperCase();

给我的结果是:HWIAWDFJCC,但我也需要维护这些点。

但这并不能解决我的问题。

您可以将这两个操作组合在一个链式方法中——首先删除多余的空格,然后按空格拆分,最后按句点拆分。

let ex1="Hello World I'm a web.dev from.japan.com cool"
//Needed solution 1 : HWIAW.DF.J.CC
let ex2= "Hello World This   is awesome";
//Needed solution 2 : HWTIA
const trans = (str) => str.replace(/  +/g, ' ').split(' ').map(s => s.split('.').map(t => t[0]).join('.')).join('').toUpperCase() ;
console.log(trans(ex1));
console.log(trans(ex2));

var s = "Hello World This   is awesome"
let split = (s) => s.split(" ") //splitting based on space
.filter((w) => w !== "") //filtering empty string created by consecutive spaces
.map((word) => word.split('.') //splttting based on .
.map((spl) => spl[0].toUpperCase()) //returning first uppercase letter
.join('.')) //joining splitted . array
.join("") //final join
console.log(split(s));
console.log(split("Hello World I'm a web.dev from.japan.com cool"));

这适用于

let sentence = "   Hello World    I'm a web.dev from.japan.com cool"
let chunks = sentence.trim().split(/[s]+/g);
let result = '';
chunks.forEach(str => {
if (str.includes('.')) {
let word = "";
for (let i = 0; i < str.length; i++) {
if (str[i] === '.') {
result += word[0];
word = "";
result += str[i];
} else {
word += str[i];
}
}
result += word[0];
} else {
result += str[0];
}
});

result = result.toUpperCase();
console.log(result);

这也是一个工作版本。

let str1 = "Hello World I'm a web.dev from.japan.com cool";
let str2 = "Hello World This   is awesome";
function getFirstLetters(parameter) {
const array = [];
const str = parameter.replaceAll('.', ' ');
let firstLetters = "";
array.push(str.split(" "));
array.forEach(item => {
for (let i = 0; i < array[0].length; i++) {
firstLetters += item[i].charAt(0);
}
});
return firstLetters.toUpperCase();
}
console.log(getFirstLetters(str1));
console.log(getFirstLetters(str2));

相关内容

  • 没有找到相关文章

最新更新