Search a string for words in array - javascript

Not seeing the error in my ways...
I am trying to search a string with keywords from an array and I just keep coming up with no results, please help me see what I am doing wrong here.
var stringArray = ["Trans", "Diode", "Label"];
var str = "Label, SpotChem Pipettes Oversticker";
var a = (stringArray.indexOf(str) > -1);
var b = (str.indexOf(stringArray) > -1);
console.log("a: " + a + " b: " + b);
//even using jquery: $.inArray(str, stringArray) returns -1
...
If needed you can see this code in a FIDDLE

You need to compare each word of the array to the string in question. You can use Array.some
var containsKeyWords = stringArray.some(word => str.indexOf(word) > -1);

Related

Adding dashes to a string at certain indexes [duplicate]

I have two variables and need to insert string b into string a at the point represented by position. The result I'm looking for is "I want an apple". How can I do this with JavaScript?
var a = 'I want apple';
var b = ' an';
var position = 6;
var a = "I want apple";
var b = " an";
var position = 6;
var output = [a.slice(0, position), b, a.slice(position)].join('');
console.log(output);
Optional: As a prototype method of String
The following can be used to splice text within another string at a desired index, with an optional removeCount parameter.
if (String.prototype.splice === undefined) {
/**
* Splices text within a string.
* #param {int} offset The position to insert the text at (before)
* #param {string} text The text to insert
* #param {int} [removeCount=0] An optional number of characters to overwrite
* #returns {string} A modified string containing the spliced text.
*/
String.prototype.splice = function(offset, text, removeCount=0) {
let calculatedOffset = offset < 0 ? this.length + offset : offset;
return this.substring(0, calculatedOffset) +
text + this.substring(calculatedOffset + removeCount);
};
}
let originalText = "I want apple";
// Positive offset
console.log(originalText.splice(6, " an"));
// Negative index
console.log(originalText.splice(-5, "an "));
// Chaining
console.log(originalText.splice(6, " an").splice(2, "need", 4).splice(0, "You", 1));
.as-console-wrapper { top: 0; max-height: 100% !important; }
var output = a.substring(0, position) + b + a.substring(position);
Edit: replaced .substr with .substring because .substr is now a legacy function (per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)
You can add this function to string class
String.prototype.insert_at=function(index, string)
{
return this.substr(0, index) + string + this.substr(index);
}
so that you can use it on any string object:
var my_string = "abcd";
my_string.insertAt(1, "XX");
Using ES6 string literals, would be much shorter:
const insertAt = (str, sub, pos) => `${str.slice(0, pos)}${sub}${str.slice(pos)}`;
console.log(insertAt('I want apple', ' an', 6)) // logs 'I want an apple'
Maybe it's even better if you determine position using indexOf() like this:
function insertString(a, b, at)
{
var position = a.indexOf(at);
if (position !== -1)
{
return a.substr(0, position) + b + a.substr(position);
}
return "substring not found";
}
then call the function like this:
insertString("I want apple", "an ", "apple");
Note, that I put a space after the "an " in the function call, rather than in the return statement.
try
a.slice(0,position) + b + a.slice(position)
var a = "I want apple";
var b = " an";
var position = 6;
var r= a.slice(0,position) + b + a.slice(position);
console.log(r);
or regexp solution
"I want apple".replace(/^(.{6})/,"$1 an")
var a = "I want apple";
var b = " an";
var position = 6;
var r= a.replace(new RegExp(`^(.{${position}})`),"$1"+b);
console.log(r);
console.log("I want apple".replace(/^(.{6})/,"$1 an"));
The Underscore.String library has a function that does Insert
insert(string, index, substring) => string
like so
insert("I want apple", 6, " an");
// => "I want an apple"
If ES2018's lookbehind is available, one more regexp solution, that makes use of it to "replace" at a zero-width position after the Nth character (similar to #Kamil Kiełczewski's, but without storing the initial characters in a capturing group):
"I want apple".replace(/(?<=^.{6})/, " an")
var a = "I want apple";
var b = " an";
var position = 6;
var r= a.replace(new RegExp(`(?<=^.{${position}})`), b);
console.log(r);
console.log("I want apple".replace(/(?<=^.{6})/, " an"));
var array = a.split(' ');
array.splice(position, 0, b);
var output = array.join(' ');
This would be slower, but will take care of the addition of space before and after the an
Also, you'll have to change the value of position ( to 2, it's more intuitive now)
Quick fix! If you don't want to manually add a space, you can do this:
var a = "I want apple";
var b = "an";
var position = 6;
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');
console.log(output);
(edit: i see that this is actually answered above, sorry!)
Well just a small change 'cause the above solution outputs
"I want anapple"
instead of
"I want an apple"
To get the output as
"I want an apple"
use the following modified code
var output = a.substr(0, position) + " " + b + a.substr(position);
With RegExp replace
var a = 'I want apple';
var b = ' an';
var position = 6;
var output = a.replace(new RegExp(`^(.{${position}})(.*)`), `$1${b}$2`);
console.log(output);
Info:
String.prototype.replace()
RegExp

Match numbers in a String only once

I´ve got this code, but now I´m trying to match numbers only once.
var text = "91308543 v1_Printer 91308543 v2 91503362 v1_Printer";
var regex = /9\d{7}/g;
var result = text.match(regex);
var pos0 = result[0];
var pos1 = result[1];
var pos2 = result[2];
return(pos0 + " " + pos1 + " " + pos2);
Result is: 91308543 91308543 91503362
Result I want: 91308543 91503362
It is possible to add something to my regex so it doesn´t show duplicate values?
I prefer not to use Arrays because in that case I need to use Native Arrays...
I also have a second question, it is possible to create the variables "pos0", "pos1"... automatically?
Thank you!
The regex you are looking for is
(9\d{7})\b(?!.*\1\b)
It uses negative lookahead. See demo.
The second point is achievable through eval:
var result = text.match(regex);
for (var i = 0; i < result.length; i++){
eval('var pos' + i + ' = "' + result[i] + '"');
}
but this does not help you with the return statement.
You should just use:
return(result.join(" "));
You can filter out the duplicates after matching, and use a destructuring assingment to assign to individual variables:
let text = "91308543 v1_Printer 91308543 v2 91503362 v1_Printer";
let regex = /9\d{7}/g;
let [pos0, pos1, pos2] = text.match(regex).filter((v, i, a) => a.indexOf(v) === i);
console.log(pos0);
console.log(pos1);
console.log(pos2);
Try this pattern (9\d{7})(?!.*\1) negative lookahead .Its not allow the duplicate
Demo regex
For more reference
var text = "91308543 v1_Printer 91308543 v2 91503362 v1_Printer";
var regex = /(9\d{7})(?!.*\1)/g;
var result = text.match(regex);
console.log(result)

Regex with dynamic requirement

Suppose I have string:
var a = '/c/Slug-A/Slug-B/Slug-C'
I have 3 possibility:
var b = 'Slug-A' || 'Slug-B' || 'Slug-C'
My expectation:
if (b === 'Slug-A') return 'Slug B - Slug C';
if (b === 'Slug-B') return 'Slug A - Slug C';
if (b === 'Slug-C') return 'Slug A - Slug B';
What I've done so far:
a.replace(b,'')
.replace(/\/c\//,'') // clear /c/
.replace(/-/g,' ')
.replace(/\//g,' - ')
Then, I'm stuck
Any help would be appreciated. Thanks
Try this:
var a = '/c/Slug-A/Slug-B/Slug-C'
var b = 'Slug-A' || 'Slug-B' || 'Slug-C'
var reg = new RegExp(b.replace(/([A-z]$)/,function(val){return '[^'+val+']'}),'g');
a.match(reg).map(function(val){return val.replace('-',' ')}).join(' - ');
Explication:
the replacement of the string b catch the last latter of the string and replace it with the ^ regex sign. this mean that instead of capture it it will ignore it.
That mean that mean that now it will match only the Slag- that isn't contain the last char.
All there is to do is to return it with any join you like.
Try this, I made it as simple as possible.
var a = '/c/Slug-A/Slug-B/Slug-C';
var b = 'Slug-A';
var regex = new RegExp(b+'|\/c\/|-|\/','g');
alert(a.replace(regex, " ").trim().replace(/(\s.*?)\s+/,'$1 - '));
//OR
alert(a.replace(regex, " ").trim().match(/\w+\s\w/g).join(' - '));
Explanation
1) b+'|\/c\/|-|\/','g' = matches b value, /c/ , - and /
2) a.replace(regex, " ") = replace all the matched part by space. so a would beSlug A Slug B
3) .replace(/(\s.*?)\s+/,'$1 - ') = match two spaces with anything within the spaces. And then replace it with the match + ' - ' appended to it.
Note that we have grouped the part (\s.*?) in the regex (\s.*?)\s+. So this grouping is done so that It can be used while replacing it with a new text. $1 holds the grouped part of the matched text so $1 = " A". So what I am doing is I match the regex Eg : " A " and replace only the grouped part ie " A" with " A" + " - " = " A - ".
4) .match(/\w+\s\w/g).join(' - ') = match all the part where characters followed by a space followed by a character. match will return a array of matched parts. So then I join this array by using join.
Do it this way
var a = '/c/Slug-A/Slug-B/Slug-C'
var b = 'Slug-A'
//var b = 'Slug-B'
//var b = 'Slug-C'
var k = a.replace(b,'')
.replace(/\/c\//,'') // clear /c/
.replace(/-/g,' ')
.match(/[a-zA-Z -]+/g).join(" - ")
console.log(k)
working array here

Formatting a JS array into specific string

I have a Javascript array
var arr = ['[dim].[att].&[123]','[dim].[att5].&[123]','[dim4].[att].&[123]','[dim3].[att].&[123]','[dim].[att].&[222]']
from this array I need to produce output like this:
var str = " 'dim'[att] = 123 || 'dim'[att] = 222 , 'dim'[att5] = 123 , 'dim4'[att] = 123 , 'dim3'[att] = 123 ";.
I first need to split each value in the array by .& and then I need to group all the items by index 0 of the resultant array. So in this case I will group [dim].[att].&[123] & [dim].[att].&[222] becuase of [dim].[att]
From each of these items, now I need to split by ]. and produce requires output such that [dim].[att].&[123] becomes 'dim'[att] = 123
I do not want to use multiple for loops for this purpose. I already have that solution ready. So far i am able to group the items, but not sure how to generate required output. Check this fiddle for my solution
You just need to use Array.map and Array.join
var str = arr.map(function(s){
var a = s.match(/\w+/g);
return "'" + a[0] + "'[" + a[1] + "] = " + a[2];
}).join("||");
In the above, we are taking the three parts which we want into an Array using s.match(/\w+/g) and then returning in the format we want.
Also, at last, Array.join is called with || as the String
DEMO
I was looking for this; Code below and DEMO
var arr = ['[dim].[att].&[123]', '[dim].[att5].&[123]', '[dim4].[att].&[123]', '[dim3].[att].&[123]', '[dim].[att].&[222]']
var res = _.chain(arr)
.groupBy(function (x) {
return x.match(/.+?\.&/i)[0];
})
.map(function(y) {
return _.map(y, function (z) {
var a = z.match(/\w+/g);
return "'" + a[0] + "'[" + a[1] + "] = " + a[2];
}).join(" || ");
})
.value().join(", ");
console.log(res)

Count occurrence times of each character in string

I have a string like this:
(apple,apple,orange,banana,strawberry,strawberry,strawberry). I want to count the number of occurrences for each of the characters, e.g. banana (1) apple(2) and strawberry(3). how can I do this?
The closest i could find was something like, which i dont know how to adapt for my needs:
function countOcurrences(str, value){
var regExp = new RegExp(value, "gi");
return str.match(regExp) ? str.match(regExp).length : 0;
}
Here is the easiest way to achieve that by using arrays.. without any expressions or stuff. Code is fairly simple and self explanatory along with comments:
var str = "apple,apple,orange,banana,strawberry,strawberry,strawberry";
var arr = str.split(','); //getting the array of all fruits
var counts = {}; //this array will contain count of each element at it's specific position, counts['apples']
arr.forEach(function(x) { counts[x] = (counts[x] || 0)+1; }); //checking and addition logic.. e.g. counts['apples']+1
alert("Apples: " + counts['apple']);
alert("Oranges: " + counts['orange']);
alert("Banana: " + counts['banana']);
alert("Strawberry: " + counts['strawberry']);
See the DEMO here
You can try
var wordCounts = str.split(",").reduce(function(result, word){
result[word] = (result[word] || 0) + 1;
return result;
}, {});
wordCounts will be a hash {"apple":2, "orange":1, ...}
You can print it as the format you like.
See the DEMO http://repl.it/YCO/10
You can use split also:
function getCount(str,d) {
return str.split(d).length - 1;
}
getCount("fat math cat", "at"); // return 3

Categories

Resources