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

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

内容简介:若要判斷 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 結束


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

查看所有标签

猜你喜欢:

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

免费

免费

克里斯•安德森 / 蒋旭峰、冯斌、璩静 / 中信出版社 / 2012-10 / 68.00元

一种商业模式既可以统摄未来的市场,也可以挤垮当前的市场——在我们这个现代经济社会里,这并不是一件不可能的事情。 “免费”就是这样的一种商业模式,它所代表的正是数字化网络时代的商业未来。 在《免费》这本书中,克里斯•安德森认为,新型的“免费”并不是一种左口袋出、右口袋进的营销伎俩,而是一种把货物和服务的成本压低到零的新型卓越能力。在20世纪“免费”是一种强有力的推销手段,而在21世纪它已经成为......一起来看看 《免费》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具