I'm expecting this to return false, as the first string is "pass / fail" and the string that is passed into IndexOf is "Numerical Specification".
Am I not understanding how this function works? I thought it checks if string A is contained within string B?
you probably meant to use "".contains, which returns an up/down boolean instead of a match index:
"abc".includes("b"); // == true;
"abc".includes("x"); // == false;
since -1 in js is "truthy", your indexOf() usage won't work as a conditional.
The indexOf() method returns the position of the first occurrence of a specified value in a string.This method returns -1 if the value to search for never occurs.
For example:
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome"); //output 13
Similiaryly:
var str = "Hello world";
var n = str.indexOf("welcome"); //output -1
Related
How to check in javascript if my string contains any of the characters ~ and β.
Is there a way to achieve this using regular expression match test, rather than writing a for loop to check if my string contains any of there characters using indexOf()
regex.test(str); is the thing you want to check. It looks in str if it is mathing regex, true if it does, else false
var a = "hey";
var b = "h~y";
var c = "heβ";
var reg = /[β~]/ ;
console.log(reg.test(a)); // false
console.log(reg.test(b)); // true
console.log(reg.test(c)) // true
Just try to find given string using indexOf() it will return value greater than -1. If value is 0,1 or any number then true else false.
var string = "Some Text'";
if (string.indexOf("~") > -1 || string.indexOf("'") > -1)
{
console.log("contains");
}else{
console.log("not contains");
}
Very new to javascript so bear with me...
I need to check one element of an array(arr[1]), which contains a string, against another element of the same array(arr[0]) to determine if any letters included in element arr[1] are included in arr[0]. Those letters can be in any order, upper or lower case, and don't have to occur the same number of times (i.e. arr[0]="hheyyy" and arr[1]="hey" is fine). This is what i have (which works) but I was curious if anyone has a better/more simple way of doing this? -thanks in advance.
function mutation(arr) {
//splits the array into two separate arrays of individual letters
var newArr0 = arr.join('').toLowerCase().split('').slice(0,arr[0].length);
var newArr1 = arr.join('').toLowerCase().split('').slice(arr[0].length);
var boolArr = [];
//checks each letter of arr1 to see if it is included in any letter of arr0
for(var i = 0; i < newArr1.length; i++)
boolArr.push(newArr0.includes(newArr1[i]));
//results are pushed into an array of boolean values
if (boolArr.indexOf(false) !==-1)
return false; //if any of those values are false return false
else return true;
}
mutation(["hello", "hey"]); //returns false
You could use a regular expression:
function mutationReg(arr) {
return !arr[1].replace(new RegExp('['+arr[0].replace(/(.)/g,'\\\\$1')+']', "gi"), '').length;
}
This escapes every character in the second string with backslash (so it cannot conflict with regular expression syntax), surrounds it with square brackets, and uses that as a search pattern on the first string. Any matches (case-insensitive) are removed from the result, so that only characters are left over that don't occur in the second string. The length of the result is thus an indication on whether there was success or not. Applying the ! to it gives the correct boolean result.
This might not be the fastest solution.
Here is another ES6 alternative using a Set for good performance:
function mutation(arr) {
var chars = new Set([...arr[0].toLowerCase()]);
return [...arr[1].toLowerCase()].every (c => chars.has(c));
}
You can use Array.from() to convert string to an array, Array.prototype.every(), String.prototype.indexOf() to check if every charactcer in string converted to array is contained in string of other array element.
var arr = ["abc", "cab"];
var bool = Array.from(arr[0]).every(el => arr[1].indexOf(el) > -1);
console.log(bool);
I have a quick question.
How do I check whether there are any commas or dashes in a string? Thx
/[,\-]/.test(yourString)
this returns true if yourString contains commas or dashes or false otherwise.
/(,|-)/.test(yourString); // returns true if there are commas or dashes in the string, false otherwise.
You can use the indexOf() method to check the presence of a substring inside a string. If the return value is greater or equal to 0 there is at least one occurrence of the substring :
var str1 = "my-string";
var str2 = "string, mine";
var str3 "simple";
str1.indexOf("-"); //returns 2
str2.indexOf(","); //returns 6
str3.indexOf("-"); //returns -1
Use
var n = str.indexOf("some. text, here");
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
Just checking index of , or -
Example code:
var str="dhfdshf-43sf";
if(str.indexOf('-')!=-1){
//- exist
}
var str2="dhfdshf,43sf";
if(str.indexOf(',')!=-1){
// , exist
}
I want to check if my string contain particular substring.
1.What function should i use to perform this in javascript or jquery or using regex
for example
var a = "i am string";
var b = "i am webpage";
if(var_a_has_string)
{
alert("it is string")
}
if(var_b_has_webpage)
{
alert("it is webpage")
}
sorry for repetition being a beginner i found some similar question but did not get the given answers here
https://stackoverflow.com/questions/5038105/checking-if-a-string-contains-a-certain-substring
Fastest way to check a string contain another substring in Javascript?
2.which function to be used if i want to retrieve the particular substring from my string
like "webpage" string or "string" string
for example
var a = "i am string";
var b = "i am webpage";
if(var_a_has_string)
{
var c = get_string_from_a(a)
}
if(var_b_has_webpage)
{
var d = get_webpage_from_b(b)
}
Just like the other answers.. string.indexOf is what you're looking for. It tells you the location of the substring within the string you're checking. -1 for not found.
var stringToCheck = "i am stringpage";
var a = "i am string";
var b = "i am webpage";
if(stringToCheck.indexOf(a) > -1){
alert("it is string")
}
if(stringToCheck.indexOf(b) > -1){
alert("it is webpage")
}
JSFIDDLE
You can use the javascript function "indexOf"
It returns an integer, and -1 if the string hasn't been found.
if (yourString.indexOf("stringToCheck") >= 0){
//Insert some logic here
}
As mentioned, indexOf is what you need.
The MDN documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
To check if string contains another substring using Javascript use the below code
var str = "Hello world, welcome to Javascript Coding.";
var n = str.indexOf("welcome");
//Returns 13
var s = "foo";
console.log(s.indexOf("oo") > -1)
//returns true
The other way to do the same thing is using includes
var str = "Hello World, Welcome to Javascript Coding";
console.log(str.includes("Welcome to")); // true
console.log(str.includes("Javascript")); // true
console.log(str.includes("To be", 1)); // false
Say, I have a string
"hello is it me you're looking for"
I want to cut part of this string out and return the new string, something like
s = string.cut(0,3);
s would now be equal to:
"lo is it me you're looking for"
EDIT: It may not be from 0 to 3. It could be from 5 to 7.
s = string.cut(5,7);
would return
"hellos it me you're looking for"
You're almost there. What you want is:
http://www.w3schools.com/jsref/jsref_substr.asp
So, in your example:
Var string = "hello is it me you're looking for";
s = string.substr(3);
As only providing a start (the first arg) takes from that index to the end of the string.
Update, how about something like:
function cut(str, cutStart, cutEnd){
return str.substr(0,cutStart) + str.substr(cutEnd+1);
}
Use
substring
function
Returns a subset of a string between
one index and another, or through the
end of the string.
substring(indexA, [indexB]);
indexA
An integer between 0 and one less than the length of the string.
indexB
(optional) An integer between 0 and the length of the string.
substring extracts characters from indexA up to but not including indexB. In particular:
* If indexA equals indexB, substring returns an empty string.
* If indexB is omitted, substring extracts characters to the end
of the string.
* If either argument is less than 0 or is NaN, it is treated as if
it were 0.
* If either argument is greater than stringName.length, it is treated as
if it were stringName.length.
If indexA is larger than indexB, then the effect of substring is as if the two arguments were swapped; for example, str.substring(1, 0) == str.substring(0, 1).
Some other more modern alternatives are:
Split and join
function cutFromString(oldStr, fullStr) {
return fullStr.split(oldStr).join('');
}
cutFromString('there ', 'Hello there world!'); // "Hello world!"
Adapted from MDN example
String.replace(), which uses regex. This means it can be more flexible with case sensitivity.
function cutFromString(oldStrRegex, fullStr) {
return fullStr.replace(oldStrRegex, '');
}
cutFromString(/there /i , 'Hello THERE world!'); // "Hello world!"
s = string.cut(5,7);
I'd prefer to do it as a separate function, but if you really want to be able to call it directly on a String from the prototype:
String.prototype.cut= function(i0, i1) {
return this.substring(0, i0)+this.substring(i1);
}
string.substring() is what you want.
Just as a reference for anyone looking for similar function, I have a String.prototype.bisect implementation that splits a string 3-ways using a regex/string delimiter and returns the before,delimiter-match and after parts of the string....
/*
Splits a string 3-ways along delimiter.
Delimiter can be a regex or a string.
Returns an array with [before,delimiter,after]
*/
String.prototype.bisect = function( delimiter){
var i,m,l=1;
if(typeof delimiter == 'string') i = this.indexOf(delimiter);
if(delimiter.exec){
m = this.match(delimiter);
i = m.index;
l = m[0].length
}
if(!i) i = this.length/2;
var res=[],temp;
if(temp = this.substring(0,i)) res.push(temp);
if(temp = this.substr(i,l)) res.push(temp);
if(temp = this.substring(i+l)) res.push(temp);
if(res.length == 3) return res;
return null;
};
/* though one could achieve similar and more optimal results for above with: */
"my string to split and get the before after splitting on and once".split(/and(.+)/,2)
// outputs => ["my string to split ", " get the before after splitting on and once"]
As stated here: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/split
If separator is a regular expression that contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array. However, not all browsers support this capability.
You need to do something like the following:
var s = "I am a string";
var sSubstring = s.substring(2); // sSubstring now equals "am a string".
You have two options about how to go about it:
http://www.quirksmode.org/js/strings.html#substring
http://www.quirksmode.org/js/strings.html#substr
Try the following:
var str="hello is it me you're looking for";
document.write(str.substring(3)+"<br />");
You can check this link
this works well
function stringCutter(str,cutCount,caretPos){
let firstPart = str.substring(0,caretPos-cutCount);
let secondPart = str.substring(caretPos,str.length);
return firstPart + secondPart;
}