首页 > 解决方案 > 从三个句子中间取出单词的最快方法是什么?/ 操作字符串

问题描述

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

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


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

预先感谢您的帮助

标签: javascriptstringmethodsangular7

解决方案


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

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

此外,还不清楚您是要保留“º”还是将其替换为“°”,因为您在问题中同时使用了这两个符号。我选择了前者,如果您需要帮助来改变它,请告诉我。

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);


推荐阅读