How can I determine if a string contains one of the values from an array?
For example:
var a = ["abc","def","ghi"];
var s = "jskljfdkljflkjk abc jskfdjklsj";
for(var i=0;i<a.length;i++){
if(/a[i]/.test(s)) alert(1);
}
This obviously doens't work... I know it's very possible though hahaha
Your syntax for creating the regular expression is incorrect. That regex will only return true for a string "ai". And you're testing the regular expression against the array. I think what you meant to write is:
if(RegExp(a[i]).test(s)) alert(1);
You would probably be better off just using indexOf in this case. It'll be faster and you won't need to escape any characters.
var a = ["abc","def","ghi"],
s = "jskljfdkljflkjk abc jskfdjklsj";
for(var i = 0, l = a.length; i < l; i++)
if(s.indexOf(a[i])+1) alert('string s contains a value from array a');
function doesStringContainElementFromArray(str, arr)
{
for ( var i=0; i<arr.length; i++)
{
if ( str.indexOf(arr[i]) != -1 )
return true;
}
return false;
}
Just use the "RegExp" function/constructor (if you really need regexps)
if (RegExp(a[i]).test(a)) {
alert(1);
}
if you don't, just use .indexOf
if (s.indexOf(a[i]) != -1) {
alert("a[i]="+a[i]+" is matched in " + s);
}
You can use search method of JavaScript
var a = ["abc","def","ghi"];
var s = "jskljfdkljflkjk abc jskfdjklsj";
for(var i=0;i<a.length;i++){
if(s.search( a[i] ) != -1)
{
alert("found");
}
}
Related
I heard, that string in JavaScript has immutability.
So, how can I write a method to replace some character in string?
What I want is:
String.prototype.replaceChar(char1, char2) {
for (var i = 0; i < this.length; i++) {
if (this[i] == char1) {
this[i] = char2;
}
}
return this;
}
Then, I can use it like this:
'abc'.replaceChar('a','b'); // bbc
I know it will not work, because the immutability of string.
But in native code, I can use the native replace method like this:
'abc'.replace(/a/g,'b');
I don't really know how to solve this problem.
You can use the following approach:
String.prototype.replaceAll = function(search, replacement) {
return this.replace(new RegExp(search, 'g'), replacement);
};
You can use array, too:
String.prototype.replaceChar = function (char1, char2) {
newstr=[];
for (i = 0; i < this.length; i++) {
newstr.push(this[i]);
if (newstr[i] == char1) {
newstr[i] = char2
}
}
return newstr.join("");
}
console.log('abca'.replaceChar('a','G'));
If you want a solution without regex (as a way to learn), you can use the following:
String.prototype.replaceChar = function(char1, char2) {
var s = this.toString();
for (var i = 0; i < s.length; i++) {
if (s[i] == char1) {
s = s.slice(0, i) + char2 + s.slice(i+1);
}
}
return s;
}
console.log('aaabaaa'.replaceChar('a', 'c'))
The idea is that you need this content of the string in a temp variable, then you need to go char-by-char, and if that char is the one you are looking for - you need to build your string again.
for(var j=0; j<product.image_groups[0].images.length; j++){
console.log("images in json" + product.image_groups[0].images[j].link)
}
This product.image_groups[0].images[j].link returns a a URL for example:
http://images.domain.com/is/image/domain/hbeu50274296_021_11
http://images.domain.com/is/image/domain/hbeu50274296_021_10
http://images.domain.com/is/image/domain/hbeu50274296_021_21
Within the loop I want to save only the URL that ends in _21 into a variable not sure how I would do this. I guess with a regex but how exactly?
Use string.match function. The below match function will match the string only if it end's with a _21 substring. $ asserts that we are at the end of a line.
for(var j=0; j<product.image_groups[0].images.length; j++){
if (product.image_groups[0].images[j].link.match(/_21$/)) {
console.log("images in json" + product.image_groups[0].images[j].link)
}
}
OR
Use regex.test function.
for(var j=0; j<product.image_groups[0].images.length; j++){
if (/_21$/.test(product.image_groups[0].images[j].link)) {
console.log("images in json" + product.image_groups[0].images[j].link)
}
}
Example:
var l = ["http://images.domain.com/is/image/domain/hbeu50274296_021_11","http://images.domain.com/is/image/domain/hbeu50274296_021_10","http://images.domain.com/is/image/domain/hbeu50274296_021_21"];
for (i=0;i<l.length;i++) {
if(l[i].match(/_21$/)) {
console.log(l[i])
}
}
Output:
http://images.domain.com/is/image/domain/hbeu50274296_021_21
You can reduce the list of images into new list, on given requirement. The easiest way to check, as for me - simply using indexOf method.
var images = product.image_groups[0].images;
var results = images.reduce(function (list, url) {
if (url.indexOf('_21') === url.length - 3) {
list.push(url);
}
return list;
}, []);
// use results here
You could split the url by _ and check the last value to see if it's 21. Something like this:
for (var j = 0; j < product.image_groups[0].images.length; j++) {
var finalPart = product.image_groups[0].images[j].link.split('_').pop();
if (finalPart == '21') {
// do something...
}
}
Try that, clean, simple and fast.
var allImages = product.image_groups[0].images;
for ( //make a for to get all images
var j
in allImages
) {
if (allImages[j].link.slice(-2) == "21") { //check if last 2 characters are "21";
console.log("images in json" + allImages[j].link);
}
}
Hi all I'm learning Javascript with the Stoyan Stefanov's book. I'm stuck on Chapter 4 Exercise 4:
Imagine the String()constructor didn't exist. Create a constructor
function MyString()that acts like String()as closely as possible.
You're not allowed to use any built-in string methods or properties,
and remember that String()doesn't exist. You can use this code to
test your constructor:
>>> var s = new MyString('hello');
>>> s[0];
"h"
I can't think on a way to achieve "s[0]", at least not with the knowledge I have now.
Any thoughts?
Thanks
Objects can have properties of themselves defined using array like syntax. String chars can be accessed with array like syntax.
function MyString (str) {
this.length = 0; // string length
var i = 0;
while(str[i] != undefined) {
this.length++;
i++;
}
for (var i=0; i< this.length;i++)
{
this[i]=str[i];
}
}
var s=new MyString('hello');
alert(s[0]); //h
here is my solution for this exercice :
function MyString(msg){
var array_msg = msg.split("");
array_msg.toString = function(){
return array_msg.join("");
};
array_msg.valueOf = function(){
return array_msg.toString();
};
array_msg.charAt = function(i){
if(array_msg[i] === undefined){
return array_msg[0];
}else{return array_msg[i];}
};
array_msg.concat = function(msg2){
return array_msg.join("")+" "+msg2;
};
array_msg.slice = function(d,f){
var res = "";
if(f<0){
f = array_msg.length + f;
}
for(var i=d; i<f; i++){
res += array_msg[i]
}
return res;
};
array_msg.split = function(el){
return array_msg.toString().split(el);
};
return array_msg;
}
A slight variation of the above...more of a tweak than anything
var MyString = function (s) {
for (var i = 0; i < s.length; i++){
this[i] = s[i]
}
this.length = function() .....
You also don't need to assign it to anything as extra as the comment suggests. this[i] will be created for the length of the string passed to s
EDIT:
Part of the question in the book says not to use existing string methods so can't use charAt so I've switched it to s[I]
This is another variation of one of the above solutions but instead of using a for loop I am using a while loop. I don't usually use while loops for these kinds of things but it worked really well here.
Adding the length property is optional.
function MyString(str) {
this.length = 0; // Creating an optional length property
this.value = str;
var i = 0;
while(str[i] != undefined) {
this[i] = str[i];
this.length++;
i++;
}
}
var name = new MyString('billy');
console.log(name.value); // 'billy'
console.log(name[0]); // 'b'
console.log(name.length); // 5
I wrote a simple 'replaceAll' function that extends String.prototype.
String.prototype.replaceAll = function (removalChar, insertionChar) {
var output = "";
for (var i = 0; i < this.length; i++) {
if(this[i] == removalChar) {
output += insertionChar;
}
else {
output += this[i];
}
}
return output;
}
Test code:
var test = "Hello-1-2-3";
alert(test.replaceAll("-"," "));
My test code alerts Hello 1 2 3 in all browsers including IE9.
But in IE7 and 8, the output I get is something like this: undefinedundefinedundefinedundefinedundefinedundefined...
jsFiddle: http://jsfiddle.net/cd4Z2/
(try this in IE7/IE8)
How could I possibly rewrite the function to ensure it works on IE7/8 without breaking its behaviour on other browsers?
You can't access string chars with this[i] in IE7/8. Use .charAt(i) instead, as explained here:
Javascript strings - getting the char at a certain point
Updated fiddle (tested in IE8): http://jsfiddle.net/cd4Z2/2/
I've just replaced this[i] with this.charAt(i).
In this question, some good reasons are stated on why you'd prefer to use charAt as opposed to string[index]. The latter is not part of ECMAScript 3.
IE<9 don't treat a string like an array, i.e. they lack ability to refer individual letter with index. You can use a temporary array (var temp = this.split('');) instead of this[i]
Try this out:-
String.prototype.replaceAll = function (removalChar, insertionChar) {
var output = "";
var res = this.split('');
for (var i = 0; i < this.length; i++) {
if(res[i] == removalChar) {
output += insertionChar;
}
else {
output += res[i];
}
}
return output;
}
var test = "Hello-1-2-3";
//alert(test.replace("-"," "));
alert(test.replaceAll("-"," "));
I am trying to learn if there is a javascript method to search a string to see if that string contains any of the values in an array of strings.
An example would be:
var a = 'How now brown cow';
var b = new Array('red', 'green', 'brown');
The resulting function would return true because the word brown is contained within the string a .
More specifically what I am trying to do (except using values from form input) is:
var a = '12345#gmail.com';
var b = new Array('.com', '.net', '.org');
This should also return true. Then based on this I will go on to accept var a as valid.
My actual code as of right now (which always returns null) is as follows:
function check_domain(){
for(var i=0; i<domains.length; i++){
var d = domains[i];
if(elemen.value.indexOf(d) != d){
return null;
}
else{
vEmail.style.visibility = 'visible';
}
}
}
window.domains = new Array(....Array values here....);
You can create a regular expression from the array:
var re = new RegExp(domains.join('|').replace(/\./g,'\\.'));
Then you can test a string:
var a = '12345#gmail.com';
var found = re.test(a);
Not sure why you've got .indexOf(d) != d. Shouldn't it be:
function check_domain(){
var d, i;
for(i = 0; i < domains.length; i++){
d = domains[i];
if(elemen.value.indexOf(d) != -1) {
return true;
}
}
}
Yes, there is something called Regular Expressions, if you really need it to match values in an array you can create a loop and check for each word against the string, something like this:
var a = 'How now brown cow';
var b = new Array('red', 'green', 'brown');
function Check(target, lookFor)
{
for(var I = 0, L = lookFor.length; I <= L; I++)
if(new RegExp(lookFor[I]).test(target))
return true;
return false;
}
alert(Check(a, b));
But in your case, the best way to go about this is just to join all the words you want to look for in the target string inside only one regular expression, so you avoid using a loop.
if(/(\.com|\.net|\.org)$/.test("sfdsdfsdf#gmail.com"))
{
// Valid email
}
else
{
// Invalid email
}