How to check if a string “StartsWith” another stri

2018-12-31 02:42发布

How would I write the equivalent of C#'s String.StartsWith in JavaScript?

var haystack = 'hello world';
var needle = 'he';

haystack.startsWith(needle) == true

Note: This is an old question, and as pointed out in the comments ECMAScript 2015 (ES6) introduced the .startsWith method. However, at the time of writing this update (2015) browser support is far from complete.

16条回答
余生请多指教
2楼-- · 2018-12-31 03:07

Best solution:

function startsWith(str, word) {
    return str.lastIndexOf(word, 0) === 0;
}

startsWith("aaa", "a")
true
startsWith("aaa", "ab")
false
startsWith("abc", "abc")
true
startsWith("abc", "c")
false
startsWith("abc", "a")
true
startsWith("abc", "ba")
false
startsWith("abc", "ab")
true

And here is endsWith if you need that too:

function endsWith(str, word) {
    return str.indexOf(word, str.length - word.length) !== -1;
}

For those that prefer to prototype it into String:

String.prototype.startsWith || (String.prototype.startsWith = function(word) {
    return this.lastIndexOf(word, 0) === 0;
});

String.prototype.endsWith   || (String.prototype.endsWith = function(word) {
    return this.indexOf(word, this.length - word.length) !== -1;
});

Usage:

"abc".startsWith("ab")
true
"c".ensdWith("c") 
true
查看更多
无与为乐者.
3楼-- · 2018-12-31 03:07

Also check out underscore.string.js. It comes with a bunch of useful string testing and manipulation methods, including a startsWith method. From the docs:

startsWith _.startsWith(string, starts)

This method checks whether string starts with starts.

_("image.gif").startsWith("image")
=> true
查看更多
骚的不知所云
4楼-- · 2018-12-31 03:08

Based on the answers here, this is the version I am now using, as it seems to give the best performance based on JSPerf testing (and is functionally complete as far as I can tell).

if(typeof String.prototype.startsWith != 'function'){
    String.prototype.startsWith = function(str){
        if(str == null) return false;
        var i = str.length;
        if(this.length < i) return false;
        for(--i; (i >= 0) && (this[i] === str[i]); --i) continue;
        return i < 0;
    }
}

This was based on startsWith2 from here: http://jsperf.com/startswith2/6. I added a small tweak for a tiny performance improvement, and have since also added a check for the comparison string being null or undefined, and converted it to add to the String prototype using the technique in CMS's answer.

Note that this implementation doesn't support the "position" parameter which is mentioned in this Mozilla Developer Network page, but that doesn't seem to be part of the ECMAScript proposal anyway.

查看更多
素衣白纱
5楼-- · 2018-12-31 03:12

I just learned about this string library:

http://stringjs.com/

Include the js file and then use the S variable like this:

S('hi there').endsWith('hi there')

It can also be used in NodeJS by installing it:

npm install string

Then requiring it as the S variable:

var S = require('string');

The web page also has links to alternate string libraries, if this one doesn't take your fancy.

查看更多
春风洒进眼中
6楼-- · 2018-12-31 03:14

Here is a minor improvement to CMS's solution:

if(!String.prototype.startsWith){
    String.prototype.startsWith = function (str) {
        return !this.indexOf(str);
    }
}

"Hello World!".startsWith("He"); // true

 var data = "Hello world";
 var input = 'He';
 data.startsWith(input); // true

Checking whether the function already exists in case a future browser implements it in native code or if it is implemented by another library. For example, the Prototype Library implements this function already.

Using ! is slightly faster and more concise than === 0 though not as readable.

查看更多
闭嘴吧你
7楼-- · 2018-12-31 03:17
var str = 'hol';
var data = 'hola mundo';
if (data.length >= str.length && data.substring(0, str.length) == str)
    return true;
else
    return false;
查看更多
登录 后发表回答