使用 endsWith() 判斷是否以特定 String 結束
栏目: JavaScript · 发布时间: 7年前
内容简介:若要判斷 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。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
数学与泛型编程
[美]亚历山大 A. 斯捷潘诺夫(Alexander A. Stepanov)、[美]丹尼尔 E. 罗斯(Daniel E. Rose) / 爱飞翔 / 机械工业出版社 / 2017-8 / 79
这是一本内容丰富而又通俗易懂的书籍,由优秀的软件设计师 Alexander A. Stepanov 与其同事 Daniel E. Rose 所撰写。作者在书中解释泛型编程的原则及其所依据的抽象数学概念,以帮助你写出简洁而强大的代码。 只要你对编程相当熟悉,并且擅长逻辑思考,那么就可以顺利阅读本书。Stepanov 与 Rose 会清晰地讲解相关的抽象代数及数论知识。他们首先解释数学家想要解决......一起来看看 《数学与泛型编程》 这本书的介绍吧!