JavaScript or jQuery string ends with utility function - javascript

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

Related

How to get the NUMBER of same characters from a paragraph using jQuery?

is it possible to get the number of SAME letters from a pararaph using jQuery? so let's say I have this paragraph:
<div>like this printer</div>
I would like to get the number of characters for "i" meaning that I should get 3 since there are 3 "i"s. I was thinking about using $(div:contains(i)), but now sure how to implement this. Any suggestions? Thanks a lot!
//Your string
var str = "I like this printer";
//Shows the count of "i" in your string.
console.log(str.replace(/[^i]/g, "").length);
Happy Coding!
Try this demo:
var src = $('#src').text();
var count = (src.match(/i/g) || []).length;
$('#count').append(count);
alert(count);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="src">like this printer</div>
<p id="count"><strong>Count of "i" = </strong></p>
use .text().split()
$('div').text().split('i').length - 1;
Firstly, you should understand :contains selector. Lastly, you can try this.
$("div:contains('i')").html().split('').reduce(function(p, n) {
return n === 'i' ? ++p : p;
}, 0);
Almost all (all?) of the solutions proposed thus far will fail if the character being searched for is "special" to Regex's (for example, '.').
Here is a method which works regardless of the character being searched for (because it doesn't use a regex):
function countInstancesOf ( str, i ) {
var count = 0;
var pos = -1;
while ((pos = str.indexOf(i, pos+1)) !== -1) ++count;
return count;
}
var howmany = countInstancesOf( $('div').text(), 'i' );
Here is a method based on String.match() and Array.length:
function countSameCharsInElement(char,string){
string.match(new RegExp(char, "g")) || []).length);
}
Sample usage:
countSameCharsInElement('i',$('div').text());
your answering own question. look up contains for strings in JavaScript. an easy to reference for a lot things web is w3 schools.
look there you will find your answer
I recommend you do some more web searching before asking stack overflow.

Extract sub string from last in a string JS [duplicate]

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.

test string against multiple regexes in javascript

I want to test a given string against 20 or so regular expressions. What's a clean way to do this in Javascript? I'm more concerned about clean code and readability than efficiency (but I don't want it to be super slow either).
Right now I have:
if (href.indexOf('apple.com') > -1 ||
href.indexOf('google.com') > -1 ||
href.indexOf('yahoo.com') > -1 ||
href.indexOf('facebook.com') > -1) {
performDarkMagic()
}
But it's going to start looking kind of messy as that list grows.
Maybe I could just create an array of regular expressions and execute something like _.any() and apply regex.test on each?
Edit: the strings/regexes to match may become more complicated, I just used simple URLs to make the example readable.
Use the test function for regular expressions.
More information on regular expressions here.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
var re = /((google)|(facebook)|(yahoo)|(apple))\.com/;
re.test( str ); // returns true or false;
Test cases.
Live Demo Here:
http://jsfiddle.net/rkzXP/1/
var func = function( str ){
var re = /((google)|(facebook)|(yahoo)|(apple))\.com/;
return re.test( str );
};
test("test for valid values", function() {
equal( func("google.com"), true);
equal( func("facebook.com"), true);
equal( func("apple.com"), true);
});
test("test for invalid values", function() {
equal( func("googl.com"), false);
equal( func("faceook.com"), false);
equal( func("apple"), false);
});
So you can rewrite your code as the following.
var re = /((google)|(facebook)|(yahoo)|(apple))\.com/;
if( re.test(str) ){
performDarkMagic()
}
var patterns = ['apple.com', 'google.com', 'yahoo.com', 'facebook.com', ...]
var callFunc = false;
patterns.forEach(function(item){
if(href.indexOf(item) > -1){
callFunc = true;
break;
}
});
if(callFunc) {
performDarkMagic();
}
Yes, building an array and using .any() or .some() is just fine, especially when there will be more than 4 values:
if (["apple","google","yahoo","facebook"].some(host => href.includes(`${host}.com`)) {
performLightMagic();
}
Yet I can't see regexes there, there are just strings; so you could simplify using regex.test() to:
if (/apple\.com|google\.com|yahoo\.com|facebook\.com/.test(href)) { performLightMagic(); }
or even
if (/(apple|google|yahoo|facebook)\.com/.test(href)) { performLightMagic(); }
You could put each one in array then looping over each.
How I would do it: factor it out into a function. Put each regex in an array, loop over them and return true the first time indexOf > -1. If you reach the end of the loop return false.
Loop through a regex array and then do:
result=result AND (result_of_regex);
next;
after the loop return result

Split string into array with Javascript in IE8

I have a string which needs to be split by three underscore characters. An example of the string might be:
var stringItemsPlanner = "Hello this___is a string___which___needs splitting into___an array";
So I use the Split() function. Fine in everything but IE8 (and probably 7 too but not tried) which gives an "Object doesn't support this property or method" error if the string doesn't contain those characters. So I found another post which said to check that the underscore characters appear in the string before splitting, so I do this:
if (stringItemsPlanner.indexOf('___') == -1){
arrItemsPlanner = [];
}else{
arrItemsPlanner = stringItemsPlanner.split('___');
}
But now this errors too because apparently IE8 doesn't support 'indexOf'.
After a lot of searching I've tried adding some code to the top of my script to act as a 'polyfil' for this method:
if (!Array.prototype.indexOf){
Array.prototype.indexOf = function(elt /*, from*/){
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)? Math.ceil(from) : Math.floor(from);
if (from < 0){
from += len;
for (; from < len; from++){
if (from in this && this[from] === elt){
return from;
}
return -1;
};
}
}
}
But still no joy.
I'm now past the point of frustration and can't really think of any other way to get this simple thing to work.
Can anyone shed any light on this or think of an alternative way to safely split a string to an array in a way that works cross-browser? It's got to be simple but I just can't think straight now.
Thanks all!
Have a look here
http://jsfiddle.net/mplungjan/Bnx6m/
var stringItemsPlanner = "Hello this___is a string___which___needs splitting into___an array";
var arrItemsPlanner = (stringItemsPlanner.length==0 || stringItemsPlanner.indexOf('___') == -1)? []:stringItemsPlanner.split('___');
alert(arrItemsPlanner.join('\n'))

How can I validate image sizes (expressed as e.g. “5X4”) using JavaScript?

I have to do image size validation using JavaScript. The sizes are provided as text, in the form nXn — e.g. “5X4” or something.
I have done a test for whether the provided size contains an “X”:
if(inputVal.indexOf("X")==-1)
{
$('#erSize').append("*Size should be (e.g) 6X4");
}
But this test accepts e.g. “aXg” also.
How can I check that the values entered either side of "X" are only integers?
Use Regular Expressions
var pattern = /[0-9]\X[0-9]/;
inp = "AXG"; //Sample
if(!pattern.test(inp))
alert("Error");
http://jsfiddle.net/hFTJb/
if(/^\d+X\d+$/.test(inputVal)) // add i after the pattern to match x case-insensitive
{
$('#erSize').append("*Size should be (e.g) 6X4");
}
// accepts "1X1"
// accepts "9999X9999"
// rejects "aaa1X1aaa"
RegEx is probably the best way, I'll give "raw" example without regular expressions that is doing the same thing:
function ValidateImageSize(imgSize) {
var arrDimensions = imgSize.toUpperCase().split("X");
if (arrDimensions.length != 2)
return false;
var w = arrDimensions[0] * 1;
var h = arrDimensions[1] * 1;
return !isNaN(w) && !isNaN(h) && w > 0 && h > 0;
}
Usage:
if (!ValidateImageSize(inputVal)) {
$('#erSize').append("*Size should be (e.g) 6X4");
}
Giving it as it's more readable than RegEx and you can control and understand each step.
Live test case.
You can easily do that by using the RegEx.
Use the regular expression as /(\d+)X(\d+)/g
function isValidInput() {
var regex = new RegExp(/(\d+)X(\d+)/g);
var match = regex.exec(inputVal);
if (match == null) {
$('#erSize').append("*Size should be (e.g) 6X4");
} else {
// here 'match' will be an array of 2 numeric values [D,D] where d is an integer.
}
}

Categories