使用 endsWith() 判斷是否以特定 String 結束
栏目: JavaScript · 发布时间: 5年前
内容简介:若要判斷 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()
let data = 'FP in JavaScript'; // endsWith :: String -> String -> Boolean let endsWith = postfix => str => str.endsWith(postfix); endsWith('JavaScript')(data); // ?
ES6 新增了 String.prototype.endsWith()
,可直接進行比較,語意更佳。
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()
整合所有流程,非常清楚。
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
:回傳判斷結果
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
:回傳判斷結果
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。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- Delphi:检查文件是否正在使用中
- 使用 startsWith() 判斷是否以特定 String 開始
- 如何使用XposedOrNot来判断自己的密码是否泄露
- SpringBoot系列之使用自定义注解校验用户是否登录
- c# – 使用ConcurrentBag作为ConcurrentDictionary的对象是否正确
- 最简洁的方法是使用Java比较三个对象是否相等?
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Programming in Haskell
Graham Hutton / Cambridge University Press / 2007-1-18 / GBP 34.99
Haskell is one of the leading languages for teaching functional programming, enabling students to write simpler and cleaner code, and to learn how to structure and reason about programs. This introduc......一起来看看 《Programming in Haskell》 这本书的介绍吧!