首页 > 解决方案 > 如何使用正则表达式使我的代码简洁明了

问题描述

我正在尝试使代码更加简洁明了。我想做的主要目标是将字符串更改为我的要求。

要求

这是我到目前为止所做的:

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)

我已经完成了大部分代码,但是,我想保留前面有 $ 的单词,大写字母,我不知道该怎么做。此外,我想知道是否可以结合正则表达式,所以它更短更简洁。

标签: javascriptnode.jsregex

解决方案


您可以使用捕获组和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);


推荐阅读