使用 endsWith() 判斷是否以特定 String 結束

栏目: JavaScript · 发布时间: 4年前

内容简介:若要判斷 String 是否以特定 String 結尾,實務上較少遇到,且實現方式也比較少。macOS Mojave 10.14.5VS Code 1.36.0

若要判斷 String 是否以特定 String 結尾,實務上較少遇到,且實現方式也比較少。

Version

macOS Mojave 10.14.5

VS Code 1.36.0

Quokka 1.0.233

Ramda 0.26.1

Regular Expression

let data = 'FP in JavaScript';

// startWith :: String -> String -> Boolean
let endsWith = postfix => str => new RegExp(`${postfix}$`).test(str);

endsWith('JavaScript')(data); // ?

最直覺方式是透過 RegExp$ 表示一行的結束。

使用 endsWith() 判斷是否以特定 String 結束

endsWith()

let data = 'FP in JavaScript';

// endsWith :: String -> String -> Boolean
let endsWith = postfix => str => str.endsWith(postfix);

endsWith('JavaScript')(data); // ?

ES6 新增了 String.prototype.endsWith() ,可直接進行比較,語意更佳。

使用 endsWith() 判斷是否以特定 String 結束

Functional

import { pipe, takeLast, equals } from 'ramda';

let data = 'FP in JavaScript';

// endsWith :: String -> String -> Boolean
let endsWith = postfix => pipe(
  takeLast(postfix.length),
  equals(postfix)
);

endsWith('JavaScript')(data); // ?

撇開 ECMAScript 內建 function,若以 functional 角度思考:

  • 使用 takeLast() 先取得 postfix 長度的 string
  • 使用 equals() 比較 takeLast() 所回傳 string 是否與 postfix 相等

最後以 pipe() 整合所有流程,非常清楚。

使用 endsWith() 判斷是否以特定 String 結束

Ramda

import { endsWith } from 'ramda';

let data = 'FP in JavaScript';

endsWith('JavaScript')(data); // ?

事實上 Ramda 已經內建 endsWith() ,可直接使用。

endsWith()

String -> String -> Boolean

判斷 string 是否以特定 string 結束

String :要判斷的特定 string

String :data 為 string

Boolean :回傳判斷結果

使用 endsWith() 判斷是否以特定 String 結束

Array

import { endsWith } from 'ramda';

let data = [1, 2, 3];

endsWith([2, 3])(data); // ?

endsWith() 不只能用在 string,也能用在 array。

endsWith()

[a] -> [a] -> Boolean

判斷 array 是否以特定 array 結束

[a] :要判斷的特定 array

[a] :data 為 array

Boolean :回傳判斷結果

使用 endsWith() 判斷是否以特定 String 結束

Object

import { endsWith } from 'ramda';

let data = [
  { title: 'FP in JavaScript', price: 300 },
  { title: 'RxJS in Action', price: 400 },
  { title: 'Speaking JavaScript', price: 200 }
];

let postfix = [
  { title: 'RxJS in Action', price: 400 },
  { title: 'Speaking JavaScript', price: 200 }
];

endsWith(postfix)(data); // ?

endsWith() 也能用在 object。

使用 endsWith() 判斷是否以特定 String 結束


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

程序是怎样跑起来的

程序是怎样跑起来的

[日] 矢泽久雄 / 李逢俊 / 人民邮电出版社 / 2015-4 / 39.00元

本书从计算机的内部结构开始讲起,以图配文的形式详细讲解了二进制、内存、数据压缩、源文件和可执行文件、操作系统和应用程序的关系、汇编语言、硬件控制方法等内容,目的是让读者了解从用户双击程序图标到程序开始运行之间到底发生了什么。同时专设了“如果是你,你会怎样介绍?”专栏,以小学生、老奶奶为对象讲解程序的运行原理,颇为有趣。本书图文并茂,通俗易懂,非常适合计算机爱好者及相关从业人员阅读。一起来看看 《程序是怎样跑起来的》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具