javascript - 如何使用正则表达式使我的代码简洁明了
问题描述
我正在尝试使代码更加简洁明了。我想做的主要目标是将字符串更改为我的要求。
要求
- 我想删除任何空行(比如下面两个句子中间的那个)
- 如果有的话,我想删除每个句子前面的 *。
- 我想让每个单词的第一个字母大写,其余小写(前面有 $ 的单词除外)
这是我到目前为止所做的:
const string =
`*SQUARE HAS ‘NO PLANS’ TO BUY MORE BITCOIN: FINANCIAL NEWS
$SQ
*$SQ UPGRADED TO OUTPERFORM FROM PERFORM AT OPPENHEIMER, PT $185`
const nostar = string.replace(/\*/g, ''); // gets rid of the * of each line
const noemptylines = nostar.replace(/^\s*[\r\n]/gm, ''); //gets rid of empty blank lines
const lowercasestring = noemptylines.toLowerCase(); //turns it to lower case
const tweets = lowercasestring.replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase()); //makes first letter of each word capital
console.log(tweets)
我已经完成了大部分代码,但是,我想保留前面有 $ 的单词,大写字母,我不知道该怎么做。此外,我想知道是否可以结合正则表达式,所以它更短更简洁。
解决方案
您可以使用捕获组和replace的回调函数。
^(\*|[\r\n]+)|\$\S*|(\S+)
^
字符串的开始(\*|[\r\n]*$)
捕获组 1,匹配一个*
或 1 个或多个换行符|
或者\$\S*
匹配$
后跟可选的非空白字符(将在代码中不加修改地返回)|
或者(\S+)
捕获组 2,匹配 1+ 非空白字符
const regex = /^(\*|[\r\n]+)|\$\S*|(\S+)/gm;
const string =
`*SQUARE HAS ‘NO PLANS’ TO BUY MORE BITCOIN: FINANCIAL NEWS
$SQ
*$SQ UPGRADED TO OUTPERFORM FROM PERFORM AT OPPENHEIMER, PT $185`;
const res = string.replace(regex, (m, g1, g2) => {
if (g1) return ""
if (g2) {
g2 = g2.toLowerCase();
return g2.toLowerCase().charAt(0).toUpperCase() + g2.slice(1);
}
return m;
});
console.log(res);
推荐阅读
- c# - 我怎样才能修复这个在运行时什么都不做的代码?
- oracle - 如何从 REST API 获取数据到 Oracle DB
- javascript - 使用带有 OOP php 类的 fetch API - 我需要 URL 吗?
- java - 创建可执行 JAR 后线程“main”java.lang.NoClassDefFoundError:org/apache/log4j/Logger 中的异常,但这是一个 JAVA 项目
- javascript - 我正在创建一个测验,但有些部分让我摸不着头脑
- oracle-sqldeveloper - 星期天出生的教职员工名单,一天的大小是9个字符长
- c# - .Net Core:从自定义异常中间件返回 IActionResult
- java - 导航视图不在工具栏内
- hyperlink -
s 使用导航时基于先前路径匹配 - python - pandas - 遍历行并计算 - 更快