javascript - 从三个句子中间取出单词的最快方法是什么?/ 操作字符串
问题描述
我有几个必须以不同方式修改的字符串
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
现在我将它们分开了,我想知道将原始句子的第二个单词放在一起的最快方法是什么……或者是否有更有效的方法来执行所需的转换
预先感谢您的帮助
解决方案
我已经在下面的代码段中评论了每个部分,您需要做的就是遍历您的字符串。
我假设您打算将每个单词大写,因为这就是您的代码所显示的内容,即使您的示例所需的输出没有显示这一点。
此外,还不清楚您是要保留“º”还是将其替换为“°”,因为您在问题中同时使用了这两个符号。我选择了前者,如果您需要帮助来改变它,请告诉我。
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);
推荐阅读
- android - 为 recyclerView 实现我自己的选择系统而不是使用 androidx.recyclerview.selection 是不是一个坏主意?
- laravel - 在 nuxt.js SSR 中,我使用 laravel sactum 创建了身份验证系统,我面临重定向错误
- r - 在R中将字符串转换为首字母缩写词的函数
- apache-spark - 两个动作的最后一个公共部分是否需要火花缓存?
- python - Python error with literals and lists in loguru: unsupported operand type(s) for +: 'NoneType' and 'list'
- pine-script - 交易所不开放时如何过滤掉bar?
- vaadin - 多模块 Vaadin 项目,其中路由视图位于独立模块中
- spring - Swagger 不显示 API 模型并且不忽略默认响应代码
- html - 无论屏幕大小如何,都使用 CSS 修复 DIV 内的 SPAN 位置
- c++ - 想提高innodb插入性能