How to get false when match finds nothing? - javascript

When I run this code:
var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = foundUrlString[1];
I get an error if there are no matches on the page:
Result of expression 'foundUrlString' [null] is not an object
How can I get "false" when there are no matches instead of this error?

Going off of what you have, you could add a "truthy" check on the second line:
var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = !!foundUrlString && foundUrlString[1];
That will leave foundUrl either as a matched string or false.

Check null to print false or true.
var savedPage = '';
var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = foundUrlString == null ? false : true;
console.log(foundUrl );

Here is an example with try and catch which may help you:
function regex(savedPage) {
try {
var foundUrlString = savedPage.match(/og:url.*="(http.*\.com)/i);
return foundUrlString[1];
} catch (error) {
return false;
}
}
var savedPage1 = '<link property="og:url" content="http://test.com/test">';
console.log('savedPage1',regex(savedPage1));
var savedPage2 = '<link content="http://test.com/test">';
console.log('savedPage2',regex(savedPage2));

You need to understand what's the purpose of String.prototype.match. The function match will return an array with the whole set of matched groups in your regexp. So, if you want to validate a string, the best way is using the function RegExp.prototype.test.
Use the function RegExp.prototype.test from regexp:
let savedPage = "EleFromStack";
console.log(/og:url.*="(http.*\.com)/i.test(savedPage));

Related

Checking if a string matches a value in an array

I really need your help,
I would like to be able to check and see if a variable matches an array value and return true if it does.
ie.
var x = "ASFA"
var array = ["OTHER-REQUEST-ASFA", "OTHER-REQUEST-ASFB", "OTHER-REQUEST-ASFC"]
alert("true")
I was thinking of using this approach, but for the life of me, I cannot get it to return true, ideas?
function test() {
var arr = ["OTHER-REQUEST-ASFA","OTHER-REQUEST-ASFB","OTHER-REQUEST-ASFC"]
if ( $.inArray('ASFA', arr) > -1 ) {
alert("true")
}
}
Try as follows
var x = "ASFA"
var array = ["OTHER-REQUEST-ASFA", "OTHER-REQUEST-ASFB", "OTHER-REQUEST-ASFC"]
array.forEach(function(ele){
console.log(ele.includes(x));
})
Quick and easy with ES6 :
let x = "ASFA",
array = ["OTHER-REQUEST-ASFA", "OTHER-REQUEST-ASFB", "OTHER-REQUEST-ASFC"],
found = array.some(elem => elem.includes(x))
console.log(found)

JavaScript get url segment and parameter

I've read some question but I still can't figure out how to do it
I have a url example.com/event/14aD9Uxp?p=10
Here I want to get the 14aD9Uxp and the value of p
I've tried using split('/'+'?p=') but it doesn't work
I want to use regex but I dont really understand how to use it
var URL='example.com/event/14aD9Uxp?p=10';
var arr=URL.split('/');//arr[0]='example.com'
//arr[1]='event'
//arr[2]='14aD9Uxp?p=10'
var parameter=arr[arr.length-1].split('?');//parameter[0]='14aD9Uxp'
//parameter[1]='p=10'
var p_value=parameter[1].split('=')[1];//p_value='10';
I've created a generalized function (restricted in some ways) that will return the GET value given the parameter. However this function will only work correctly provided that you do not Rewrite the URL or modify the URL GET SYNTAX.
//Suppose this is your URL "example.com/event/14aD9Uxp?p=10";
function GET(variable) {
var str = window.location.href;
str = str.split("/");
// str = [example.com, event, 14aD9Uxp?p=10]
//Get last item from array because this is usually where the GET parameter is located, then split with "?"
str = str[str.length - 1].split("?");
// str[str.length - 1] = "14aD9Uxp?p=10"
// str[str.length - 1].split("?") = [14aD9Uxp, p=10]
// If there is more than 1 GET parameter, they usually connected with Ampersand symbol (&). Assuming there is more, we need to split this into another array
str = str[1].split("&");
// Suppose this is your URL: example.com/event/14aD9Uxp?p=10&q=112&r=119
// str = [p=10, q=112, r=119]
// If there is only 1 GET parameter, this split() function will not "split" anything
//Remember, there might only be 1 GET Parameter, so lets check length of the array to be sure.
if (str.length > 1) {
// This is the case where there is more than 1 parameter, so we loop over the array and filter out the variable requested
for (var i = 0; i < str.length; i++) {
// For each "p=10" etc. split the equal sign
var param_full_str = str[i].split("=");
// param_full_str = [p, 10]
//Check if the first item in the array (your GET parameter) is equal to the parameter requested
if (param_full_str[0] == variable) {
// If it is equal, return the second item in the array, your GET parameter VALUE
return param_full_str[1];
}
}
} else {
// This is the case where there is ONLY 1 GET parameter. First convert it to a String Type because Javascript decided that str was no longer a String
// Now split it with the equal sign.
str = str.toString().split("=");
return str[1];
}
}
document.write(GET("p"));
function $_GET(param) {
var vars = {};
window.location.href.replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}
I have collected this from here:
http://www.creativejuiz.fr/blog/javascript/recuperer-parametres-get-url-javascript
It works great.
To use it just grab your parameter like:
var id = $_GET('id');
const url = new URL('http://example.com/event/14aD9Uxp?p=10');
const [,, eventId ] = url.pathname.split('/');
const p = url.searchParams.get('p');
Browser support:
https://caniuse.com/#feat=url
https://caniuse.com/#feat=urlsearchparams
Simple no-regex way
var s = "example.com/event/14aD9Uxp?p=10";
var splitByForwardSlash = s.split('/');
// To get 14aD9Uxp
splitByForwardSlash[splitByForwardSlash.length-1]
// To get p=10
splitByForwardSlash[splitByForwardSlash.length-1].split('?')[1]
I think you know how to go from here :-)

using match(), but it didn't work froma string variable

I have the following fiddle:
jsfiddle
The function:
$('#testbutton').on("click", function(){
test();
});
function test()
{
var data = [];
data['article'] = "monablanko";
data['specialarticle'] = ["blanko", "bbsooel"];
var tmp = data['specialarticle'].join("|");
if( data['article'].match( /(tmp)/ ) )
{
$('#result').html("I found a match");
}
else
{
$('#result').html("I didn't found a match");
}
}
I didn't found a match with this function. Where is my error? The typeof tmp is string when i use
console.log(typeof tmp);
when i write
if( data['article'].match( /(blanko|bbsooel)/ ) )
then i find a match.
You're matching against the string literal "tmp", not against the value contained inside the variable tmp. Try it like this:
data['article'].match( new RegExp("(" + tmp + ")") )
eg: http://jsfiddle.net/4K8Km/
You need to create a RegExp to match your string before:
$('#testbutton').on("click", function(){
test();
});
function test(){
var data = [];
data['article'] = "monablanko";
data['specialarticle'] = ["blanko", "bbsooel"];
var tmp = new RegExp('('+data['specialarticle'].join("|")+')');
if( data['article'].match( tmp ) )
{
$('#result').html("I found a match");
}
else
{
$('#result').html("I didn't found a match");
}
}
Just one more tip: if you don't need to collect a match, but just to test if the string has that RegExp I would suggest to use test instead of match:
tmp.test(data['article']);
rather than
data['article'].match(tmp);

Substring that exits between a recurring patern

My string is :<div>2</div><div>3</div><div>4</div><div>5</div><div><br></div>
I need to get 2,3,4,5, in an array using Javascript ie.anything between <div></div>
Whats the most elegant way to do this?
To match anything between <div> and </div>
var a, r=[];
while((s=str.indexOf("<div>"))!=-1){
e=str.indexOf("</div>");
a=str.substring(s+5, e);
if(a) r.push(a);
str=str.substr(e+6);
}
Another easier method
var r = str.match(/<div>.*?<\/div>/gi).map(function(i){
return i.replace(/<div>(.*?)<\/div>/gi, "$1");
});
If it was just digits (like in your initial question) use this
var str = "<div>2</div><div>3</div><div>4</div><div>5</div><div><br></div>";
var num = str.match(/\d+/g)
try the below code
var obj = $("div").map(function(index,value){
return $(this).html();
})
alert( "hi" +obj[0]);
http://jsfiddle.net/F9MQr/12/
For any value you could;
var s = "<div>2</div><div>3</div><div>4</div><div>5</div><div><br></div>";
var a = [];
$.each($(s).filter("div"), function() {
$(this).text() !== "" && a.push($(this).text());
});
alert(a);
​
(This would ignore empty divs & return X for <div>X<br/></div>)

How to trim variables without erring if the var is empty?

I'm using the following for event tracking:
var dataTrack = e.split(','); // split by comma
if (dataTrack !== undefined) {
var action = dataTrack[0];
var values = {};
values[dataTrack[1]] = dataTrack[2];
mpq.track(action, values);
}
How can I trim dataTrack[0], dataTrack[1], dataTrack[2] in a way where if any of the dataTrack vars are empty it won't break? 1 & 2 are optional...
Thanks
A common idiom in JavaScript is to provide default values like so:
// default to the empty string
var dataTrack0 = dataTrack[0] || '',
dataTrack1 = dataTrack[1] || '',
dataTrack2 = dataTrack[2] || '';
...though I think a better solution, in this case, might be to check the length of the array.
You probably want to use the length property for the array.
var dataTrack = e.split(','); // split by comma
if (dataTrack !== undefined) {
var action = dataTrack[0];
var values = {};
if(dataTrack.length > 2) {
values[dataTrack[1]] = dataTrack[2];
}
mpq.track(action, values);
}
You could add extra validation to check that dataTrack[ 1] has a length > 0 if it is possible that someone would pass "value1,,value3".
Couldn't you just check to make sure they are not empty? Also you could use the ternary operator to have a default value if they are empty (i.e. action == undefined ? "Default" : datatrack[0];).
Replace
values[dataTrack[1]] = dataTrack[2];
with
if(dataTrack.length > 2){
values[dataTrack[1]] = dataTrack[2];
}

Categories