.join ( ) Only Works in console.log ( ) - javascript

When I use the console.log( ) function to join this array it returns the combined array, but when I use the .join( ) function outside of console.log( ), it does not combine the array. How do I combine this array to create a single string with no comma outside of console.log( )?
var string = stringArray.map(string => "&sources=" + string);
console.log(stringURL.join(''));
stringURL.join('');
console.log(stringURL);

.join() is a function that returns the joined string. So when you call it, it calculates the value and then returns it.
Store it in a variable.
var joinedString = stringURL.join('');

Your problem is that stringURL.join(''); does modify stringURL but give a new string. so the best is to make
var new_string = stringURL.join('');
console.log(new_string);

You can't have a variable name called string, it's protected. Change it to something else and it will work.
Here's a complete list of reserved keywords and here is an explanation from Mozilla MDN
var mappedString = stringArray.map(string => "&sources=" + string);
console.log(mappedString.join(''));
var joinedString = mappedString.join('')
console.log(joinedString);
That should do!

Related

How to search for a string using each member of array as a parameter

I want to search for a string using each member of an array
I can search for an string by a string by using .includes() but would like to send in an array of strings and search by each member
// Currently searches for whole string
let lsearchText = this.config.searchText.toLowerCase()
a.Categories.toString().toLowerCase().includes(lsearchText)
// I want to search by each member of split array seperately
let lsearchText = this.config.searchText.toLowerCase().split(' ');
a.Categories.toString().toLowerCase().includes(lsearchText)
Im getting error
error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'string'.
My full function
get filteredAlbumListArray() {
if (this.config.searchText && this.config.searchText.length > 1) {
let lsearchText = this.config.searchText.toLowerCase().split(' ');
return this.albumList.filter((a) =>
a.Frequency.toLowerCase().includes(lsearchText)
||
a.Year.toString().toLowerCase().includes(lsearchText)
||
a.Title.toLowerCase().includes(lsearchText)
||
a.Categories.toString().toLowerCase().includes(lsearchText)
||
a.Description.toLowerCase().includes(lsearchText)
||
a.FieldNames.replace(/_/g, ' ').toLowerCase().includes(lsearchText)
);
}
return this.albumList;
}
So if i type in Weekly 2019 id like to return results that Are both Weekly and 2019
try somehting like this
const lsearchTexts: string[] = this.config.searchText.toLowerCase().split(' ');
lsearchTexts.some(lsearchText => a.Categories.toString().includes(lsearchText));
let result =[];
lsearchText.forEach(l=>{
if(a.Categories.includes(lsearchText)){
result.push(l);
}
})
you'll find existing members in th result array
You can split the search string and use map/filter or any other operation using it same as array. Since no example is given i'll take some random example.
searchFor = "some text";
searchIn = "some thing to search";
// using filter you can remove the not available substring
searchFor.split(" ").filter(st => searchIn.includes(st)) // prints - ["some"]
searchFor.split(" ").filter(st => searchIn.includes(st)) // prints - "some"

Possible reducer case after a map function.

I'm trying to see if array.reduce would be a better option in this case.
I'd like to return the string result instead of having to set a variable in the forEach loop.
So what I'm doing is seeing if there are any matches inside a string matching my regex. Then getting the text inside that match and replacing it with a variable I pass to it. All works great but I'd like to clean it up if I can. findReplaceTemplateString is a separate function and I'm ok with that. Its the forEach feels like I could use a reducer instead to return the completed string. But I'm new to reducers and not sure if this is a good case for it. Anyone have any thoughts on this.
const reg = /\{.+?\}/g;
const matches = tpl.match(reg);
let str = '';
matches.map(item => item.slice(1, -1)).forEach((placeHolder) => {
str = findReplace(tpl, placeHolder, props[placeHolder] || '');
});
I don't see the point of overcomplicating it. Simply use String.prototype.replace() with function as a second parameter. That will dynamically replace your pattern with valid parameters.
const input = 'Hi there, {name}! What are you doing in {city}?';
const props = {name: 'Alex', city: 'St Petersburg'};
const output = input.replace(/\{.+?\}/g, (p) => {
return props[p.slice(1, -1)] || p /* here you may use '' */;
});
console.log( output );

How to access RegExp.prototype.exec() return value?

I have an array I want to pull all the files that end in .txt, so I apply a regular expression to find all that match within
var x = ["test.txt", "random.txt", "dontgetme"]
var re = RegExp(".*\.txt", "g")
When I try to access the results via the first index, I can retrieve the correct result:
re.exec(x)[0] returns "test.txt,random.txt"
but when I try to store it in a variable, I can't access it anymore:
var y = re.exec(x)[0] returns undefined
How do I store the results of the .exec in a variable to be accessed at a later time?
You can use .filter(), .test()
var re = /\.txt$/;
var matches = x.filter(function(text) { return re.test(text) })
var y = re.exec(x)[0] returns undefined
This is because you're looking at the return value of a var statement, which always returns undefined.
You want to assign it to y and then access y, as such:
var y = re.exec(x)[0] // always undefined
console.log(y) // ok!
but when I try to store it in a variable, I can't access it anymore:
var y = re.exec(x)[0] returns undefined
You'll only see that in a REPL environment (like the console). var statements result in undefined. But y will have the value.
If you pass x directly into exec, it'll be coerced to string, and you'll end up with "test.txt,random.txt,dontgetme".
Also note that you don't want that g flag, and you do want to escape the . in .txt. There's no need for new RegExp here, just use the literal form: /.*\.txt/.
Instead of passing x into exec, to get results for each of those, use a loop of some kind. For instance, here I'm using map to create an array of the results. Inside map, I use [0] to access just the first thing in the array exec returns, as that's the only useful thing it returns for your regex:
var x = ["test.txt", "random.txt", "dontgetme"]
var re = /.*\.txt/;
var result = x.map(function(entry) {
var match = re.exec(entry);
return match ? match[0] : null;
});
console.log(result);

Getting all var from a javastring function by Regular Expression

Hi I am new for Regex and trying to get below,
there is a string below in javascript,
"function(){var a; var a,b,c;}"
and I am trying to find [a,b,c] from it.
Please suggest me to get all variable declared in string, what will be regex.
A very very manipulative solution, but will serve your purpose
function uniq(value,index,self){
return self.indexOf(value) === index;
}
var str = "function(){var a; var a,b,c;}";
var ptrn = /var [^;]+/g;
var match;
var matches = []
while ( ( match = ptrn.exec(str) ) != null )
{
matches.push(match.join().split(" ")[1]);
}
console.log(matches.join(",").split(",").filter(uniq));
but if you understand this code you wont have to ever search for:
how to get unique values from js array
how matching a pattern with exec only returns the first match and we have to loop to get the rest of the values
finally adding a filter with a function.

Javascript replace with $1 as var

I have the following situation:
There is a certain string that contains some vars, such as:
var string = '/page/{id}/{title}';
Now, I want to be able to replace {id} and {title} with the vars from the following array:
var arr = {'id':10, 'title':'test-page'};
I came up with this little regex:
string.replace ( /{([a-zA-Z0-9]+)}/g , '$1' );
Which, as expected, just returns this:
/page/id/title
So I tried this:
string.replace ( /{([a-zA-Z0-9]+)}/g , arr [ '$1' ] );
But that returns a
/page/undefined/undefined
Now, I understand that something like this would be possible with a loop et cetera, but it would be nice to have a one-liner for this. I am not very used to JS, so I hope that there is some function or option that I am unaware of that helps me out with this :).
Best regards!
Try something like this:
var arr = {'id':10, 'title':'test-page'};
'/page/{id}/{title}'.replace(/\{([\w\d]+?)\}/g, function(a, b) {
return arr[b] || '';
});
If you use this replace thing often I would create a String helper prototype method. For example:
String.prototype.template = function(data) {
return this.replace(/\{([\w\d]+?)\}/g, function(a, b) {
return data[b] || '';
});
};
and use it like this:
'/page/{id}/{title}'.template(arr);
According to MDN article,
Because we want to further
transform the result of the match before the final substitution is
made, we must use a function. This forces the evaluation of the match
prior to the toLowerCase() method. If we had tried to do this using
the match without a function, the toLowerCase() would have no effect.
(In the text above, replace toLowerCase() with "accessing property in object")
Then, you can use
function replacer(match, p1, p2, p3/*, ...*/, offset, string){
return arr[p1];
}
var arr = {'id':10, 'title':'test-page'};
'/page/{id}/{title}'.replace(/\{([\w\d]+?)\}/g, replacer);

Categories