Trying to convert string to a number, works fine apart from when the number is zero it returns an empty string;
I understand 0 is false, but I just need a neat way of it returning the string "0"
I'm using:
const num = this.str ? this.str.toString() : '' ;
I even thought of using es6 and simply ${this.str} but that didn't work
Because 0 is "false-y" in JavaScript, as you've already figured out, you can't utilized it in a conditional. Instead, ask yourself what the conditional is really trying to solve.
Are you worried about null / undefined values? Perhaps this is better:
const num = (typeof this.str !== "undefined" && this.str !== null) ? this.str.toString() : "";
Odds are you really only care if this.str is a Number, and in all other cases want to ignore it. What if this.str is a Date, or an Array? Both Date and Array have a .toString() method, which means you may have some weird bugs crop up if one slips into your function unexpectedly.
So a better solution may be:
const num = (typeof this.str === "number") ? this.str.toString() : "";
You can also put your code in a try catch block
const num = ''
try {
num = this.str.toString();
} catch(e) {
// Do something here if you want.
}
Just adding to given answers - if you do:
x >> 0
you will convert anything to a Number
'7' >> 0 // 7
'' >> 0 // 0
true >> 0 // 1
[7] >> 0 // 7
It's a right shift bit operation. You can do magic with this in many real life cases, like described in this article.
In my case, the zero (number) that I wanted to converted to a string (which was the value of an option in a select element) was a value in an enum.
So I did this, since the enum was generated by another process and I could not change it:
let stringValue = '';
if (this.input.enumValue === 0) {
stringValue = '0';
} else {
stringValue = this.input.enumValue.toString();
}
I am trying tor write this function that Check if a string (first argument, str) ends with the given target string (second argument, target). I have used this code but it seems not to work. How can i tweak it?
function confirmEnding(str, target) {
var last = str.substring(-1);
var last2 = target.substring(-1);
if (last == last2) return true;
else if (last !== last2) return false;
}
confirmEnding("Walking on water and developing software from a specification
are easy if both are frozen", "specification") )/*should return "false".
confirmEnding("Bastian", "n") should return true.
confirmEnding("Connor", "n") should return false.
confirmEnding("Walking on water and developing software from a specification
are easy if both are frozen", "specification") should return false.
confirmEnding("He has to give me a new name", "name") should return true.
confirmEnding("Open sesame", "same") should return true.
confirmEnding("Open sesame", "pen") should return false.
confirmEnding("If you want to save our world, you must hurry. We dont know
how much longer we can withstand the nothing", "mountain") should return
false.
Do not use the built-in method .endsWith() to solve the challenge.*/
In order to pass all of the tests with the desired return values, the function should not be comparing the last character of the string, but rather the entire string, target to the corresponding end substring of str. You need the length of target to find the correct starting index for the corresponding substring in str as follows:
function confirmEnding (str, target) {
return str.substr(-(target.length)) === target
}
Your code is comparing the entire strings. See substring() documentation below. -1 is defaulting to 0 thus returning the substring starting at index 0 and returning the rest of the string (the entire string) since no end index is given. .
"If either argument is less than 0 or is NaN, it is treated as if it
were 0."
You can use the substr() method instead of substring() if you want to use negative indices. substr() recognizes negative index values instead of defaulting to 0.
"If start is negative, substr() uses it as a character index from the
end of the string."
You can use the length of target and subtract it from the length of str to get the correct substring for comparison. This will return all of the characters from this index to the end of the string as in str.length - target.lengththough you only really need target.length to make the comparison using negative indices.
Using substring():
function confirmEnding (str, target) {
var last = str.substring(str.length-(target.length));
if (last == target ) return true;
else return false;
}
Using substr():
function confirmEnding (str, target) {
var last = str.substr(-(target.length));
if (last == target ) return true;
else return false;
}
or a cleaner/alternate implementation:
function confirmEnding (str, target) {
return str.substr(-(target.length) === target)
}
substr() documentation
substring() documentation
After seeing the ongoing confusion over this case (abbreviated for readability):
confirmEnding(
"Walking on water...both are frozen",
"specification"
); // Should return false (why not true?)
and also this interesting note:
/* Do not use the built-in method .endsWith() to solve the challenge. */
I have a hunch about what may have happened.
Double-check the instructions for this question. Are you sure you're supposed to test if the last character of each string is the same? It sounds like you are supposed to test if the src string ends with the entire target string.
After all, that is what the .endsWith() method does. And it explains the mystery of the test case above.
The MDN documentation for .endsWith() doesn't describe the method very well, but the examples it gives make it clear.
With that understanding, you can probably now write the code. I'm not going to write it for you, but I will drop some hints below. I added some code for your tests so that they not only log the result, but also whether they return the desired result. (In the version as written here, all the tests will fail.)
// Return true if str ends with target, false if it does not
function confirmEnding( str, target ) {
// You can do this in a single return statement
// with one === comparison in it. The .slice()
// method will help you here, and you only need
// to pass a single argument into it.
// You don't need any if statements, intermediate
// variables, or anything fancy.
// There are several other ways to do it too, including
// the approach shown on the MDN page.
}
function testEnding( str, target, desired ) {
var result = confirmEnding( str, target );
console.log(
'"' + str + '"',
'"' + target + '"',
'returns', result,
result === desired ? 'Good' : 'WRONG!'
);
}
testEnding( "Bastian", "n", true );
testEnding( "Connor", "n", false );
testEnding( "Walking on water and developing software from a specification are easy if both are frozen", "specification", false );
testEnding( "He has to give me a new name", "name", true );
testEnding( "Open sesame", "same", true );
testEnding( "Open sesame", "pen", false );
testEnding( "If you want to save our world, you must hurry ); We dont know how much longer we can withstand the nothing", "mountain", false );
You can use this function:
function confirmEnding(a, b) {
var l1 = a[a.length - 1];
var l2 = b[b.length - 1];
return l1 === l2;
}
Your error is that you're using substring. Try str.substr instead of substring
function confirmEnding (str, target) {
return str.substr(-1) == target.substr(-1);
}
console.log(confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification"));
const a = "Walking on water and developing software from a specification are easy if both are frozen",
b = "specification";
// your function
const equalLastLetter = (a, b) => a.substr(-1) === b.substr(-1);
console.log(equalLastLetter(a, b))
How about this?
function confirmEnding (str, target) {
var last = str.charAt(str.length-1);
var last2 = target.charAt(target.length-1);
return (last == last2);
}
You can use chatAt()
function confirmEnding (str, target) {
var last = str.charAt(str.length -1);
var last2 = target.charAt(target.length -1);
return last === last2 ;
}
Why have to check if last words are same so:
const confirmEnding = (str, target) => new RegExp(`${target}$`, '').test(str)
console.log(confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification"))
console.log(confirmEnding("Bastian", "n"))
console.log(confirmEnding("Connor", "n"))
console.log(confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification"))
console.log(confirmEnding("He has to give me a new name", "name"))
console.log(confirmEnding("Open sesame", "same"))
console.log(confirmEnding("Open sesame", "pen"))
console.log(confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain"))
Simplest way:
const confirmEnding = (_str, _target) => _str.charAt(_str.length - 1) === _target.charAt(_target.length - 1);
https://jsfiddle.net/pablodarde/hsdgjmzw/
So basically I wrote myself this function so as to be able to count the number of occurances of a Substring in a String:
String.prototype.numberOf = function(needle) {
var num = 0,
lastIndex = 0;
if(typeof needle === "string" || needle instanceof String) {
while((lastIndex = this.indexOf(needle, lastIndex) + 1) > 0)
{num++;} return num;
} else if(needle instanceof RegExp) {
// needle.global = true;
return this.match(needle).length;
} return 0;
};
The method itself performs rather well and both the RegExp and String based searches are quite comparable as to the execution time (both ~2ms on the entire vast Ray Bradbury's "451 Fahrenheit" searching for all the "the"s).
What sort of bothers me, though, is the impossibility of changing the flag of the supplied RegExp instance. There is no point in calling String.prototype.match in this function without the global flag of the supplied Regular Expression set to true, as it would only note the first occurance then. You could certainly set the flag manually on each RegExp passed to the function, I'd however prefer being able to clone and then manipulate the supplied Regular Expression's flags.
Astonishingly enough, I'm not permitted to do so as the RegExp.prototype.global flag (more precisely all flags) appear to be read-only. Thence the commented-out line 8.
So my question is: Is there a nice way of changing the flags of a RegExp object?
I don't really wanna do stuff like this:
if(!expression.global)
expression = eval(expression.toString() + "g");
Some implementations might not event support the RegExp.prototype.toString and simply inherit it from the Object.prototype, or it could be a different formatting entirely. And it just seems as a bad coding practice to begin with.
First, your current code does not work correctly when needle is a regex which does not match. i.e. The following line:
return this.match(needle).length;
The match method returns null when there is no match. A JavaScript error is then generated when the length property of null is (unsuccessfully) accessed. This is easily fixed like so:
var m = this.match(needle);
return m ? m.length : 0;
Now to the problem at hand. You are correct when you say that global, ignoreCase and multiline are read only properties. The only option is to create a new RegExp. This is easily done since the regex source string is stored in the re.source property. Here is a tested modified version of your function which corrects the problem above and creates a new RegExp object when needle does not already have its global flag set:
String.prototype.numberOf = function(needle) {
var num = 0,
lastIndex = 0;
if (typeof needle === "string" || needle instanceof String) {
while((lastIndex = this.indexOf(needle, lastIndex) + 1) > 0)
{num++;} return num;
} else if(needle instanceof RegExp) {
if (!needle.global) {
// If global flag not set, create new one.
var flags = "g";
if (needle.ignoreCase) flags += "i";
if (needle.multiline) flags += "m";
needle = RegExp(needle.source, flags);
}
var m = this.match(needle);
return m ? m.length : 0;
}
return 0;
};
var globalRegex = new RegExp(needle.source, "g");
Live Demo EDIT: The m was only for the sake of demonstrating that you can set multiple modifiers
var regex = /find/;
var other = new RegExp(regex.source, "gm");
alert(other.global);
alert(other.multiline);
r = new Regexp(r.source, r.flags + (r.global ? "" : "g"));
There isn't much you can do but I highly recommend you avoid using eval. You can extend the RegExp prototype to help you out.
RegExp.prototype.flags = function () {
return (this.ignoreCase ? "i" : "")
+ (this.multiline ? "m" : "")
+ (this.global ? "g" : "");
};
var reg1 = /AAA/i;
var reg2 = new RegExp(reg1.source, reg1.flags() + 'g');
How can I check if a string ends with a particular character in JavaScript?
Example: I have a string
var str = "mystring#";
I want to know if that string is ending with #. How can I check it?
Is there a endsWith() method in JavaScript?
One solution I have is take the length of the string and get the last character and check it.
Is this the best way or there is any other way?
UPDATE (Nov 24th, 2015):
This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments:
Shauna -
Update for Googlers - Looks like ECMA6 adds this function. The MDN article also shows a polyfill. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
T.J. Crowder -
Creating substrings isn't expensive on modern browsers; it may well have been in 2010 when this answer was posted. These days, the simple this.substr(-suffix.length) === suffix approach is fastest on Chrome, the same on IE11 as indexOf, and only 4% slower (fergetaboutit territory) on Firefox: https://jsben.ch/OJzlM And faster across the board when the result is false: jsperf.com/endswith-stackoverflow-when-false Of course, with ES6 adding endsWith, the point is moot. :-)
ORIGINAL ANSWER:
I know this is a year old question... but I need this too and I need it to work cross-browser so... combining everyone's answer and comments and simplifying it a bit:
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
Doesn't create a substring
Uses native indexOf function for fastest results
Skip unnecessary comparisons using the second parameter of indexOf to skip ahead
Works in Internet Explorer
NO Regex complications
Also, if you don't like stuffing things in native data structure's prototypes, here's a standalone version:
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
EDIT: As noted by #hamish in the comments, if you want to err on the safe side and check if an implementation has already been provided, you can just adds a typeof check like so:
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
/#$/.test(str)
will work on all browsers, doesn't require monkey patching String, and doesn't require scanning the entire string as lastIndexOf does when there is no match.
If you want to match a constant string that might contain regular expression special characters, such as '$', then you can use the following:
function makeSuffixRegExp(suffix, caseInsensitive) {
return new RegExp(
String(suffix).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$",
caseInsensitive ? "i" : "");
}
and then you can use it like this
makeSuffixRegExp("a[complicated]*suffix*").test(str)
Unfortunately not.
if( "mystring#".substr(-1) === "#" ) {}
Come on, this is the correct endsWith implementation:
String.prototype.endsWith = function (s) {
return this.length >= s.length && this.substr(this.length - s.length) == s;
}
using lastIndexOf just creates unnecessary CPU loops if there is no match.
This version avoids creating a substring, and doesn't use regular expressions (some regex answers here will work; others are broken):
String.prototype.endsWith = function(str)
{
var lastIndex = this.lastIndexOf(str);
return (lastIndex !== -1) && (lastIndex + str.length === this.length);
}
If performance is important to you, it would be worth testing whether lastIndexOf is actually faster than creating a substring or not. (It may well depend on the JS engine you're using...) It may well be faster in the matching case, and when the string is small - but when the string is huge it needs to look back through the whole thing even though we don't really care :(
For checking a single character, finding the length and then using charAt is probably the best way.
Didn't see apporach with slice method. So i'm just leave it here:
function endsWith(str, suffix) {
return str.slice(-suffix.length) === suffix
}
From developer.mozilla.org String.prototype.endsWith()
Summary
The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate.
Syntax
str.endsWith(searchString [, position]);
Parameters
searchString :
The characters to be searched for at the end of this string.
position :
Search within this string as if this string were only this long; defaults to this string's actual length, clamped within the range established by this string's length.
Description
This method lets you determine whether or not a string ends with another string.
Examples
var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") ); // true
alert( str.endsWith("to be") ); // false
alert( str.endsWith("to be", 19) ); // true
Specifications
ECMAScript Language Specification 6th Edition (ECMA-262)
Browser compatibility
return this.lastIndexOf(str) + str.length == this.length;
does not work in the case where original string length is one less than search string length and the search string is not found:
lastIndexOf returns -1, then you add search string length and you are left with the original string's length.
A possible fix is
return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length
if( ("mystring#").substr(-1,1) == '#' )
-- Or --
if( ("mystring#").match(/#$/) )
Just another quick alternative that worked like a charm for me, using regex:
// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}
String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}
I hope this helps
var myStr = “ Earth is a beautiful planet ”;
var myStr2 = myStr.trim();
//==“Earth is a beautiful planet”;
if (myStr2.startsWith(“Earth”)) // returns TRUE
if (myStr2.endsWith(“planet”)) // returns TRUE
if (myStr.startsWith(“Earth”))
// returns FALSE due to the leading spaces…
if (myStr.endsWith(“planet”))
// returns FALSE due to trailing spaces…
the traditional way
function strStartsWith(str, prefix) {
return str.indexOf(prefix) === 0;
}
function strEndsWith(str, suffix) {
return str.match(suffix+"$")==suffix;
}
I don't know about you, but:
var s = "mystring#";
s.length >= 1 && s[s.length - 1] == '#'; // will do the thing!
Why regular expressions? Why messing with the prototype? substr? c'mon...
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.
If you're using lodash:
_.endsWith('abc', 'c'); // true
If not using lodash, you can borrow from its source.
function strEndsWith(str,suffix) {
var reguex= new RegExp(suffix+'$');
if (str.match(reguex)!=null)
return true;
return false;
}
So many things for such a small problem, just use this Regular Expression
var str = "mystring#";
var regex = /^.*#$/
if (regex.test(str)){
//if it has a trailing '#'
}
Its been many years for this question. Let me add an important update for the users who wants to use the most voted chakrit's answer.
'endsWith' functions is already added to JavaScript as part of ECMAScript 6 (experimental technology)
Refer it here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
Hence it is highly recommended to add check for the existence of native implementation as mentioned in the answer.
function check(str)
{
var lastIndex = str.lastIndexOf('/');
return (lastIndex != -1) && (lastIndex == (str.length - 1));
}
A way to future proof and/or prevent overwriting of existing prototype would be test check to see if it has already been added to the String prototype. Here's my take on the non-regex highly rated version.
if (typeof String.endsWith !== 'function') {
String.prototype.endsWith = function (suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
#chakrit's accepted answer is a solid way to do it yourself. If, however, you're looking for a packaged solution, I recommend taking a look at underscore.string, as #mlunoe pointed out. Using underscore.string, the code would be:
function endsWithHash(str) {
return _.str.endsWith(str, '#');
}
After all those long tally of answers, i found this piece of code simple and easy to understand!
function end(str, target) {
return str.substr(-target.length) == target;
}
if you dont want to use lasIndexOf or substr then why not just look at the string in its natural state (ie. an array)
String.prototype.endsWith = function(suffix) {
if (this[this.length - 1] == suffix) return true;
return false;
}
or as a standalone function
function strEndsWith(str,suffix) {
if (str[str.length - 1] == suffix) return true;
return false;
}
String.prototype.endWith = function (a) {
var isExp = a.constructor.name === "RegExp",
val = this;
if (isExp === false) {
a = escape(a);
val = escape(val);
} else
a = a.toString().replace(/(^\/)|(\/$)/g, "");
return eval("/" + a + "$/.test(val)");
}
// example
var str = "Hello";
alert(str.endWith("lo"));
alert(str.endWith(/l(o|a)/));
This builds on #charkit's accepted answer allowing either an Array of strings, or string to passed in as an argument.
if (typeof String.prototype.endsWith === 'undefined') {
String.prototype.endsWith = function(suffix) {
if (typeof suffix === 'String') {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
}else if(suffix instanceof Array){
return _.find(suffix, function(value){
console.log(value, (this.indexOf(value, this.length - value.length) !== -1));
return this.indexOf(value, this.length - value.length) !== -1;
}, this);
}
};
}
This requires underscorejs - but can probably be adjusted to remove the underscore dependency.
if(typeof String.prototype.endsWith !== "function") {
/**
* String.prototype.endsWith
* Check if given string locate at the end of current string
* #param {string} substring substring to locate in the current string.
* #param {number=} position end the endsWith check at that position
* #return {boolean}
*
* #edition ECMA-262 6th Edition, 15.5.4.23
*/
String.prototype.endsWith = function(substring, position) {
substring = String(substring);
var subLen = substring.length | 0;
if( !subLen )return true;//Empty string
var strLen = this.length;
if( position === void 0 )position = strLen;
else position = position | 0;
if( position < 1 )return false;
var fromIndex = (strLen < position ? strLen : position) - subLen;
return (fromIndex >= 0 || subLen === -fromIndex)
&& (
position === 0
// if position not at the and of the string, we can optimise search substring
// by checking first symbol of substring exists in search position in current string
|| this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false
)
&& this.indexOf(substring, fromIndex) === fromIndex
;
};
}
Benefits:
This version is not just re-using indexOf.
Greatest performance on long strings. Here is a speed test http://jsperf.com/starts-ends-with/4
Fully compatible with ecmascript specification. It passes the tests
Do not use regular expressions. They are slow even in fast languages. Just write a function that checks the end of a string. This library has nice examples: groundjs/util.js.
Be careful adding a function to String.prototype. This code has nice examples of how to do it: groundjs/prototype.js
In general, this is a nice language-level library: groundjs
You can also take a look at lodash
all of them are very useful examples. Adding String.prototype.endsWith = function(str) will help us to simply call the method to check if our string ends with it or not, well regexp will also do it.
I found a better solution than mine. Thanks every one.
For coffeescript
String::endsWith = (suffix) ->
-1 != #indexOf suffix, #length - suffix.length
This is the implementation of endsWith:
String.prototype.endsWith = function (str) {
return (this.length >= str.length) && (this.substr(this.length - str.length) === str);
}
7 years old post, but I was not able to understand top few posts, because they are complex. So, I wrote my own solution:
function strEndsWith(str, endwith)
{
var lastIndex = url.lastIndexOf(endsWith);
var result = false;
if (lastIndex > 0 && (lastIndex + "registerc".length) == url.length)
{
result = true;
}
return result;
}