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
`
Related
So I have a function that checks if the last character in a string is an arithmetic operator(+,-,*,/), and if it is it should immediately return from the function. If not, the subtract sign should be appended to the string. However, only the second case seems to be occurring and I can't figure out why. If anyone could provide some insight I would be very appreciative.
$("#subtract").click(function () {
var original=$("#display").text();
var sliced=original.slice(0,original.length - 1);
var signs=["+","-","*","/"];
var charpos=sliced.charAt(sliced.length -1);
if ((charpos === signs[0]) || (charpos === signs[1]) || (charpos === signs[2]) || (charpos === signs[3])) {
return;
}
else {
var newdisplay=sliced + "-";
$("#display").text(newdisplay);
}
});
You're slicing the input which is removing the last character, then using charAt and getting the second to last character.
var original=$("#display").text(); // "foobar"
var sliced=original.slice(0,original.length - 1); // "fooba"
var charpos=sliced.charAt(sliced.length -1); // "a" -- we lost the "r"
You only need to call charAt and work with the last character (or, if you prefer slice, it's able to accept a negative number and backtrack the string).
Secondly, since signs is an array, you can use indexOf over checking each element. e.g.
var original = $('#display').text();
var signs = ["+","-","*","/"];
var lastChar = original.slice(-1); // OR original.charAt(original.length - 1);
// Check for the lastChar in the signs array
if (signs.indexOf(lastChar) != -1){ // -1 == not found
return; // short exit
}
var original=$("#display").text();
var sliced=original.slice(0,original.length - 1);
the second line gets rid of the last character in your string. so you're not even able to check what that was. just get rid of it and change the first line to
var sliced=$("#display").text();
and everything should work fine
Instead of
if ((charpos === signs[0]) || (charpos === signs[1]) || (charpos === signs[2]) || (charpos === signs[3])) {
return;
}
try
if ($.inArray(charpos, signs) > -1) {
return;
}
First of all, never enumerate items from an array in such a fashion - it's easy to miss items that way. Secondly, exact instance comparison (===) won't fire, unless you compared exact same strings.
Besides, consider revising how you extract the last character.
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(".", ""); ?
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.
How can I get the first "word" out of these strings?
/User/Edit/
/Admin/Edit/2
/Tags/Add
I should get User, Admin, Tags, etc
http://jsfiddle.net/RV5r2/1/
as simple as this. since you split it up in an array, just return the first element:
return ar[1];
and youre ready to go ;)
or you could reverse() first and the pop() :D but this migth be a bit odd. just be sure you check if the array key [1] is set! by
return (typeof ar[1] !== 'undefined') ? ar[1] : '';
Or again:
return ar.slice(1,2);
I would recommend that you change a bit the logic in your lastWord method (note: lastWord is not a good name for this method - maybe firstWord?) to take in account paths/strings which don't start with "/" and paths that don't contain "/"
function lastWord(subject)
{
var ar = subject.split("/");
if(ar.length >= 2)
{
//we have at least one / in our string
if(ar[0] !== "") {
//the string doesn't start with /
return ar[0];
}
else {
//if the strings starts with / then the ar[0] will be ""
return ar[1];
}
}
else {
//we return an empty string if the input was not valid, you could handle this differently
return "";
}
}
This way :
"/some/amazing/sentence" will return "some"
"some/amazing/sentence" will return "some"
"someamazingsentence" will return ""
I have to check whether a form field contains '#' at start of user input & is it contains it at all. It works fine for checking if its at start of the string. But when I add checking whether input contains '#' at all or not. It fails. Here is my code
function email_valid(field)
{
var apos=field.update.value;
apos=apos.indexOf('#');
if (apos>0 ||((apos.contains('#')== 'FALSE')))
{ alert('plz enter valid input');
return false;
}
else
{ return true; }
}
EDIT
This function in this form is checking both if # is at 1st place & 2ndly is it in the input at all or not.
function #_valid(field)
{
var ref=field.update.value;// I needed ref 4 other things
var apos=ref.indexOf('#');
if (apos>=0 )
{
if (apos==0)
{
return true;
}
else { field.t_update3.value="";
alert('plz enter a valid refernce');
return false;
}
}
else { field.t_update3.value="";
alert('plz enter a valid refernce');
return false;
} }
Consider:
var apos = value.indexOf('#');
if (apos >= 0) {
// was found in string, somewhere
if (apos == 0) {
// was at start
} else {
// was elsewhere
}
} else {
// not in string
}
and
var apos = value.indexOf('#');
if (apos == 0) {
// was at start
} else if (apos > 0) {
// was elsewhere
} else {
// not in string
}
Why not just
if (apos !== 0) { /* error; */ }
The "apos" value will be the numeric value zero when your input is (as I understand it) valid, and either -1 or greater than 0 when invalid.
This seems like a strange thing to make a user of your site do, but whatever. (If it's not there at all, and it must be there to be valid, why can't you just add the "#" for the user?)
You can just check to make sure that apos is greater than -1. Javascript's indexOf() will return the current index of the character you're looking for and -1 if it's not in the string.
edit Misread a bit. Also make sure that it's not equal to 0, so that it's not at the beginning of the string.
function email_valid(field)
{
var fieldValue =field.update.value;
var apos = apos.indexOf('#');
if (apos > 0 || apos < 0)//could also use apos !== 0
{ alert('plz enter valid input');
return false;
}
else
{ return true; }
}
apos is the value returned by indexOf, it will be -1 if there is no # in the user input. It will be 0 if it is the first character. It will be greater than 0 if the user input contains an # . JavaScript has no contains method on a String.
Try:
function email_valid(field) {
//var apos=field.update.value;
var apos = field;
//apos=apos.indexOf('#');
apos = apos.indexOf('#');
if( (apos < 0) ) {
//alert('plz enter valid input');
alert('false');
} else {
alert('true');
}
}
email_valid('blah');
Checks for # anywhere. Or, if you want to check for # just at the beginning, change if( (apos < 0) ) { to if( (apos == 0) ) {. Or, if you want to make sure it's not at the beginning, then if( (apos > 0) ) {.
apos will be -1 if the string was not found. So your code should be as follows:
function email_valid(field)
{
var apos=field.value;
apos=apos.indexOf('#');
if (apos<=0) // handles '#' at the beginning and not in string at all.
{
alert('plz enter valid input');
return false;
}
else
{ return true; }
}
I also changed your initial assignment to remove the .update portion as that would cause it to fail when field is a reference to an input.
In the second if condition, apos is a number, not a string.
You're trying to write
if (field.update.value.charAt(0) == '#' && field.update.value.indexOf('#', 1) < 0)
Learn about Regular expressions if you haven't already. Then lookup Javascript's String#match. There is no need to find wether the input starts with an "#" as if it contains an "#" that will also return true if the "#" is at the start of the string.
Also, for free, return true and return false are generally bad style. Just return the thing you passed to if (that evaluates to a boolean).
All in all:
function validate_input(str) {
return str.match(/#/);
}
I reccomend passing the function a string (field.value or some-such) rather than the field itself as it makes it more generic.
Update: revised answer based on comments. code below will only return true if the value contains an "#" symbol at the first character.
If this is a JavaScript question, then this should be fine.
function email_valid(field){
var apos=field.update.value;
if(apos.indexOf('#') != 0){
alert('plz enter valid input');
return false;
} else {
//field contains an '#' at the first position (index zero)
return true;
}
}
That said, your parameter "field" if it actually refers to an input field element, should only require this code to get the value (e.g. I'm not sure where the ".update" bit comes into play)
var apos = field.value;
I would also rename this function if it isn't doing "email validation" to something a little more appropriately named.