一、使用正则
String.prototype.startWith = function(str) { var reg = new RegExp("^" + str); return reg.test(this); } String.prototype.endWith = function(str) { var reg = new RegExp(str + "$"); return reg.test(this); }
使用正则看似简单,但是调用时要注意特殊字符的转义,如/ \ . * + ? | ( ) { } [ ]
str.endWith("\\|"); 要经过两次转义
二、使用普通js
String.prototype.endWith = function(s) { if (s == null || s == "" || this.length == 0 || s.length > this.length) return false; if (this.substring(this.length - s.length) == s) return true; else return false; //return true; } String.prototype.startWith = function(s) { if (s == null || s == "" || this.length == 0 || s.length > this.length) return false; if (this.substr(0, s.length) == s) return true; else return false; //return true; }
JavaScript String 对象
http://www.w3school.com.cn/jsref/jsref_obj_string.asp
相关推荐
本文将详细介绍几种常用的自定义 `String` 方法,包括 `EndWith`, `StartWith`, `Trim`, `ltrim`, `rtrim` 和一个格式化函数 `String.format` 以及 JSON 对象转字符串的方法 `Json2string`。 #### 二、`EndWith` ...
在JavaScript中,函数是第一类对象,可以作为变量、参数和返回值。...在JavaScript中,还可以通过原型链自定义对象的方法,扩展内置类型的功能,如上述对String和Date对象的扩展。这些技巧对于提升代码质量至关重要。
`startWith` 和 `endWith` 方法则用于判断字符串是否以指定的字符串开头或结尾。这些方法支持区分大小写的比较,也可以不区分大小写。在不区分大小写的情况下,会先将原字符串和比较值都转换为小写(或大写),然后...
在JavaScript的世界里,`String.prototype.trim()`方法是一个非常实用的功能,它用于去除字符串两端的空白字符,如空格、制表符、换行符等。然而,在早期版本的Internet Explorer浏览器,尤其是IE8及以下版本,`trim...
ES6还为字符串对象增加了三个新方法:`startWith()`, `includes()`, 和 `endWith()`,这些方法用于检测字符串中是否存在特定的子字符串。它们类似于`indexOf()`,但提供了更直接的语法和更清晰的意图。 - `start...