修剪字符串并返回短语数组



我有一个字符串,由用=符号分隔的短语对组成。

let trapSt = 'i was sent = i sent. to protect you = to find you. they are = we are.';

请注意,每对都用点与其他对隔开。

现在我想像这样使用上面的字符串创建一个数组(每个单词之间以及单词和=符号之间只有一个空格(:

["i was sent = i sent", "to protect you = to find you", "they are = we are"] 

所以我写了这个(无论你如何定义 strig,我都试图返回上面的数组(:

let trapSt = '   i  was    sent =     i sent   .to protect    you= to find you. they are =we are.   ';
trapSt = trapSt.toLowerCase().replace(/s+/g, " ").split(".").map(s => s.trim());
trapSt = trapSt.filter(s => s);
console.log(trapSt);

如您所见,这不是我们想要的:我们想要to protect you = to find you而不是to protect you= to find you

我怎样才能做到这一点?

试试这个:

let trapSt = '   i  was    sent =     i sent   .to protect    you= to find you. they are =we are.   ';
trapSt = trapSt.toLowerCase().replace(/s+/g, " ").split(".").map(s => s.trim());
trapSt = trapSt.map(s => s.split("=").map(s => s.trim()).join(" = "));  // split each element again by "=", trim it, and join it again
trapSt = trapSt.filter(s => s);
console.log(trapSt);

  1. 按句点吐痰
  2. 修剪每块
    1. 将 = 替换为用空格包围的 =(这可能会引入双倍间距(
    2. 删除所有重复间距
  3. 筛选出要在结束期间处理的任何空白字符串结果

let trapSt = '   i  was    sent =     i sent   .to protect    you= to find you. they are =we are.   ';
console.log(
trapSt.split('.')
.map(it => it.trim().replace(/=/, ' = ').replace(/s{2,}/g, ' ') )
.filter(it => it)
);

相关内容

  • 没有找到相关文章

最新更新