This question already has answers here:
endsWith in JavaScript
(30 answers)
Closed 9 years ago.
I need to write JS function which returns true if string contains - depreciated in its last otherwise false.
For example:
var somestring = "string value - depreciated";
function should return true in above example.
function isDepreciated(var S)
{
//Need to check for substring in last
//return true or false
}
One possible solution is to use search function but that means that if - depreciated comes within string then it will also return true. I really need to find weather substring is in last or not.
Please help.
Add the below code in your JS
function isDepreciated(string){
return /(-depreciated)$/.test(string);
}
You'll want to use the Javascript string method .substr() combined with the .length property.
function isDepreciated(var id)
{
var id = "string value - depreciated";
var lastdepreciated = id.substr(id.length - 13); // => "- depreciated"
//return true or false check for true or flase
}
This gets the characters starting at id.length - 13 and, since the second argument for .substr() is omitted, continues to the end of the string.
function isDepreciated(S) {
var suffix = "- depreciated";
return S.indexOf(suffix, S.length - suffix.length) !== -1;
}
You could use currying: http://ejohn.org/blog/partial-functions-in-javascript/
Function.prototype.curry = function() {
var fn = this, args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply(this, args.concat(
Array.prototype.slice.call(arguments)));
};
};
With the helper curry function you could create your isDepricated check:
String.prototype.isDepricated = String.prototype.match.curry(/- depreciated$/);
"string value - depreciated".isDepricated();
Or use .bind():
var isDepricated = RegExp.prototype.test.bind(/- depreciated$/);
isDepricated("string value - depreciated");
function isDepreciated(S){
return (new RegExp(" - depriciated$").test(S));
}
how about just use regular expression
var myRe=/depreciated$/;
var myval = "string value - depreciated";
if (myRe.exec(myval)) {
alert ('found');
}
else{
alert('not found');
}
lots of answers are already here (the one with $ is preferred), even though i also had to write one, so it will also do your job,
var somestring = "string value - depreciated";
var pattern="- depreciated";
function isDepreciated(var s)
{
b=s.substring(s.length-pattern.length,s.length)==pattern;
}
function isDeprecated(str) {
return ((str.indexOf("- depreciated") == str.length - "- depreciated".length) ? true : false);
}
isDeprecated("this")
false
isDeprecated("this - depreciated")
true
isDeprecated("this - depreciated abc")
false
Ok, I haven't run this code on a browser, but this should give a basic idea of what to do. You might have to tweak some of the conditions if needed.
var search = "- depricated";
var pos = str.indexOf(search);
if(pos > 0 && pos + search.length == str.length){
return true;
}
else{
return false;
}
Edit: indexOf() returns the start index of the string.
Related
This task requires that you write a function that takes two arguments. The first argument is a string called str and the second argument is a string that our target ending named target. The task is to verify that the ending of str is identical to the target ending. The instructions indicate to use the .substr() method to compare the endings to the targets. The problem I have is that there are going to be multiple starting points and length arguments for the .substr method since the target endings can be of variable length. Take a look at my attempt to solve this issue and please direct me in the right path.
function end(str, target) {
var start = str.length - (target.length - 1);
if(str.substr(start, str.length) == target){
return true;
} else {
return false;
}
}
end('Bastian', 'n');
EDIT
As #torazaburo said. The correct answer Is:
function end(str, target) {
return target === str.substr(str.length - target.length);
}
Because The string does end with a null string
ORIGINAL ANSWER
function end(str, target) {
return target.length > 0 && target === str.substr(str.length - target.length);
}
http://jsfiddle.net/tqsx0gLa/2/
From Comments:
This code is setting up a logical comparison using the && operator. The left side target.length > 0 should always return true with a valid target input. The left side is setting target equal to the substr starting at the point located by taking the str.length (the position at the far right of the str) and subtracting the target length (to arrive at the start point of our substring). There is no need for an end point input because the substring will run to the end of str.
Here is a easy solution :
function confirmEnding(str, target) {
var result;
//getting the last string depend on target length
var last = str.substring(str.length - target.length);
//checking the last string with the target
if(last === target){
result = true;
} else {
result = false;
}
return result;
}
function end(str, target) {
var start = str.length - target.length;
if(str.substr(start) == target){
return true;
}
else {
return false;
}
}
You can also try this code.
The substring method can take a negative value to work from the end of the string. The solution to your problem is very simple:
function end (str, target) {
return str.substr(-target.length) === target;
}
end("simple is better", "better"); // returns true
// which is the same as writing
"simple is better".substr(-6) === "better" // true again
I find this simple:
function end(str, target) {
return str.substr(-target.length) == target;
}
I like your original answer, it is clean and easy to ready.
Try removing the -1 on line 2. This way it will return all of the target word in your substr.
function end(str, target) {
var start = str.length - (target.length);
if(str.substr(start) == target){
return true;
} else {
return false;
}
}
end ("He has to give me a new name", "name")
When the sub-string does not return a second argument, it will return from the number that is start to the end of the string.
function confirmEnding(str, target) {
var position = str.length - target.length; //get start position for our .substr method.....
if (str.substr(position, target.length == target){ // logical expression wich tell our method(.substr) from which position we need get information then we compare result with our "target" argument.
return true;
} else { return false; }
}
confirmEnding("Bastian", "n"); // true
My solution uses substr method that takes the length of the target and with minus gives us the last characters of the first string for comparison.
const confirmEnding = (str, target) => str.substr(-target.length) === target ?
true :
false;
Here you go:
const solution = (str, target) => str.endsWith(target);
The cleanest way.
`
function endSearch(str, ending){
// just on line to solve this problem
// endsWith() ==> string.endsWith('string search' , position = str.length['defalut value'])
return str.endsWith(ending)
}
console.log(endSearch('abc', 'bc')) // ture
console.log(endSearch('abc', 'a')) // false
console.log(endSearch('abc', 'x')) // false
`
I want to remove decimal from number in javascript:
Something like this:
12 => 12
12.00 => 1200
12.12 => 1212
12.12.12 => error: please enter valid number.
I can not use Math.round(number). Because, it'll give me different result. How can I achieve this? Thanks.
The simplest way to handle the first three examples is:
function removeDecimal(num) {
return parseInt(num.toString().replace(".", ""), 10);
}
This assumes that the argument is a number already, in which case your second and fourth examples are impossible.
If that's not the case, you'll need to count the number of dots in the string, using something like (trick taken from this question):
(str.match(/\./g) || []).length
Combining the two and throwing, you can:
function removeDecimal(num) {
if ((num.toString().match(/\./g) || []).length > 1) throw new Error("Too many periods!");
return parseInt(num.toString().replace(".", ""), 10);
}
This will work for most numbers, but may run into rounding errors for particularly large or precise values (for example, removeDecimal("1398080348.12341234") will return 139808034812341230).
If you know the input will always be a number and you want to get really tricky, you can also do something like:
function removeDecimal(num) {
var numStr = num.toString();
if (numStr.indexOf(".") === -1) return num;
return num * Math.pow(10, numStr.length - numStr.indexOf(".") - 1);
}
You can use the replace method to remove the first period in the string, then you can check if there is another period left:
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
// invalid input
}
Demo:
function reformat(str) {
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
return "invalid input";
}
return str;
}
// show in Stackoverflow snippet
function show(str) {
document.write(str + '<br>');
}
show(reformat("12"));
show(reformat("12.00"));
show(reformat("12.12"));
show(reformat("12.12.12"));
How about number = number.replace(".", ""); ?
Here is my jsFiddle
Its on the Phone method, no the name one
Now is this line right? I only want it to be true if the first 3 letters are 087
var RightStarting3 = value.substring(0,2) == (087);
if (BlankPass || LessThan10 || RightStarting3 || GreaterThan10 || (HasSpaces > 0))
{
document.getElementById('Phone').style.background = "red";
return false;
}
else {
document.getElementById('Phone').style.background = "white";
document.getElementById("PhoneTick").style.visibility="visible";
return true;
}
var RightStarting3 = value.substring(0,3) === ('087');
value.substring(x) returns a string and 087 and 87 mean the same to javascript interpreter. You should change one of the datatypes so that they match...
Either the substring to an integer:
var RightStarting3 = parseInt(value.substring(0,2)) == 87;
Or the value you're comparing against to a string:
var RightStarting3 = value.substring(0,3) == "087";
Secondly -- you are invoking ValidateName() immediately (in your assignment to NamePass). Is this really necessary? There will be empty values on page load.
I think with the javascript substring(x,y) method, the y value is the value at which to stop the selection. So in your example the first 3 characters will not be selected and instead the first 2 characters will be selected.
var a = "123";
// this returns "12"
alert(a.substring(0,2));
You probably want to use var RightStarting3 = value.substring(0,3) == ('087'); instead.
KingKongFrom's answer is correct, I would add that you should make sure that value (whatever that is) isn't null first, cause if you try to call substring on null it will thrown an exception and die.
This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 5 years ago.
I have a shopping cart that displays product options in a dropdown menu and if they select "yes", I want to make some other fields on the page visible.
The problem is that the shopping cart also includes the price modifier in the text, which can be different for each product. The following code works:
$(document).ready(function() {
$('select[id="Engraving"]').change(function() {
var str = $('select[id="Engraving"] option:selected').text();
if (str == "Yes (+ $6.95)") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
However I would rather use something like this, which doesn't work:
$(document).ready(function() {
$('select[id="Engraving"]').change(function() {
var str = $('select[id="Engraving"] option:selected').text();
if (str *= "Yes") {
$('.engraving').show();
} else {
$('.engraving').hide();
}
});
});
I only want to perform the action if the selected option contains the word "Yes", and would ignore the price modifier.
Like this:
if (str.indexOf("Yes") >= 0)
...or you can use the tilde operator:
if (~str.indexOf("Yes"))
This works because indexOf() returns -1 if the string wasn't found at all.
Note that this is case-sensitive.
If you want a case-insensitive search, you can write
if (str.toLowerCase().indexOf("yes") >= 0)
Or:
if (/yes/i.test(str))
The latter is a regular expression or regex.
Regex breakdown:
/ indicates this is a regex
yes means that the regex will find those exact characters in that exact order
/ ends the regex
i sets the regex as case-insensitive
.test(str) determines if the regular expression matches str
To sum it up, it means it will see if it can find the letters y, e, and s in that exact order, case-insensitively, in the variable str
You could use search or match for this.
str.search( 'Yes' )
will return the position of the match, or -1 if it isn't found.
It's pretty late to write this answer, but I thought of including it anyhow. String.prototype now has a method includes which can check for substring. This method is case sensitive.
var str = 'It was a good date';
console.log(str.includes('good')); // shows true
console.log(str.includes('Good')); // shows false
To check for a substring, the following approach can be taken:
if (mainString.toLowerCase().includes(substringToCheck.toLowerCase())) {
// mainString contains substringToCheck
}
Check out the documentation to know more.
Another way:
var testStr = "This is a test";
if(testStr.contains("test")){
alert("String Found");
}
** Tested on Firefox, Safari 6 and Chrome 36 **
ECMAScript 6 introduces String.prototype.includes, previously named contains.
It can be used like this:
'foobar'.includes('foo'); // true
'foobar'.includes('baz'); // false
It also accepts an optional second argument which specifies the position at which to begin searching:
'foobar'.includes('foo', 1); // false
'foobar'.includes('bar', 1); // true
It can be polyfilled to make it work on old browsers.
The includes() method determines whether one string may be found within another string, returning true or false as appropriate.
Syntax :-string.includes(searchString[, position])
searchString:-A string to be searched for within this string.
position:-Optional. The position in this string at which to begin searching for searchString; defaults to 0.
string = 'LOL';
console.log(string.includes('lol')); // returns false
console.log(string.includes('LOL')); // returns true
You can use this Polyfill in ie and chrome
if (!('contains' in String.prototype)) {
String.prototype.contains = function (str, startIndex) {
"use strict";
return -1 !== String.prototype.indexOf.call(this, str, startIndex);
};
}
If you are capable of using libraries, you may find that Lo-Dash JS library is quite useful. In this case, go ahead and check _.contains() (replaced by _.includes() as of v4).
(Note Lo-Dash convention is naming the library object _.
Don't forget to check installation in the same page to set it up for your project.)
_.contains("foo", "oo"); // → true
_.contains("foo", "bar"); // → false
// Equivalent with:
_("foo").contains("oo"); // → true
_("foo").contains("bar"); // → false
In your case, go ahead and use:
_.contains(str, "Yes");
// or:
_(str).contains("Yes");
..whichever one you like better.
I know that best way is str.indexOf(s) !== -1; http://hayageek.com/javascript-string-contains/
I suggest another way(str.replace(s1, "") !== str):
var str = "Hello World!", s1 = "ello", s2 = "elloo";
alert(str.replace(s1, "") !== str);
alert(str.replace(s2, "") !== str);
You can also check if the exact word is contained in a string. E.g.:
function containsWord(haystack, needle) {
return (" " + haystack + " ").indexOf(" " + needle + " ") !== -1;
}
Usage:
containsWord("red green blue", "red"); // true
containsWord("red green blue", "green"); // true
containsWord("red green blue", "blue"); // true
containsWord("red green blue", "yellow"); // false
This is how jQuery does its hasClass method.
you can define an extension method and use it later.
String.prototype.contains = function(it)
{
return this.indexOf(it) != -1;
};
so that you can use in your page anywhere like:
var str="hello how are you";
str.contains("are");
which returns true.
Refer below post for more extension helper methods.
Javascript helper methods
None of the above worked for me as there were blank spaces but this is what I did
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
bottab.style.display="none";
bottab2.style.display="none";
if (td) {
var getvar=td.outerText.replace(/\s+/, "") ;
if (getvar==filter){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
}
}
what is the easiest way to figure out if a string ends with a certain value?
you could use Regexps, like this:
str.match(/value$/)
which would return true if the string has 'value' at the end of it ($).
Stolen from prototypejs:
String.prototype.endsWith = function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};
'slaughter'.endsWith('laughter');
// -> true
Regular expressions
"Hello world".match(/world$/)
I had no luck with the match approach, but this worked:
If you have the string, "This is my string." and wanted to see if it ends with a period, do this:
var myString = "This is my string.";
var stringCheck = ".";
var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
alert(foundIt);
You can change the variable stringCheck to be any string to check for. Better still would be to throw this in your own function like this:
function DoesStringEndWith(myString, stringCheck)
{
var foundIt = (myString.lastIndexOf(stringCheck) === myString.length - stringCheck.length) > 0;
return foundIt;
}
You can do 'hello world'.slice(-5)==='world'. Works in all browsers. Much faster than regex.
ES6 supports this directly:
'this is dog'.endsWith('dog') //true
I am just expanding on what #luca-matteis has posted but to solve the issues pointed out in the comments the code should be wrapped to make sure you are not overwriting a native implementation.
if ( !String.prototype.endsWith ) {
String.prototype.endsWith = function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};
}
This is the suggested method for the Array.prototype.forEach method pointed out in the mozilla developer network
You can always prototype String class, this will work:
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}
You can find other related extensions for String class in http://www.tek-tips.com/faqs.cfm?fid=6620