将单词从三个句子的中间移出的最快方法是什么? /操作字符串

问题描述 投票:0回答:1

我有几个必须以不同方式修改的字符串

const string1 = 'PACK Nº1 compressed :';
const string2 = 'PACK Nº2 compressed :';
const string3 = 'PACK Nº3 compressed :';
const string4 = 'PACK Nº4 compressed :';
const string5 = 'PACK Nº5 compressed :';

我必须将它们全部转换,以使其看起来像这样

', Pack Nº1 compressed'

为此,我得到了第一个和最后一个单词,并对它们进行了转换,并消除了我不需要的元素

    const phrase = 'PACK N°1 comprenant :';
    const result = phrase.replace(' :', ''); //to eliminate : and blank space

    const firstWord = result.replace(/ .*/,'');
    const lastWOrd = result.split(" ").pop(); // to get first and last word

    const lastWordCapitalized = lastWOrd.charAt(0).toUpperCase() + lastWOrd.slice(1); // to capitalize the first letter of the last word

    const lowerFirstWord = firstWord.toLowerCase();
    const firstWordCapitalize = lowerFirstWord.charAt(0).toUpperCase() + lowerFirstWord.slice(1); //to capitalize the first letter of the first word


现在我将它们分开,我想知道将原始句子的第二个单词放在一起的最快方法是什么,或者是否有更有效的方法执行所需的转换

感谢您的帮助

javascript string methods angular7
1个回答
0
投票

我在下面的代码段中评论了每个部分,您所需要做的就是遍历字符串。

我假设您打算将每个单词都大写,因为这就是您的代码所显示的内容,即使您的示例所需的输出未显示该内容。

也不清楚,您是否想保留“º”或将其替换为“°”?如果您需要更改方面的帮助,请与我联系。

var phrase = 'PACK Nº1 compressed :';
phrase = phrase.replace(" :",""); // get rid of the unwanted characters at the end
phrase = phrase.toLowerCase() //split by words and capitalise the first letter of each
    .split(' ')
    .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
    .join(' ');

phrase = ", " + phrase; //add the leading comma

console.log(phrase);
© www.soinside.com 2019 - 2024. All rights reserved.