Javascript : Detect if a String contain url image - javascript

I have the following String :
var str = "Hello, i would like to show this image : http://logonoid.com/images/stack-overflow-logo.png" ;
I would like to create a function which detect the presence of image urls and return a 2 things :
The new String without the image url
An array containing image url found in the String.
How can i do that ?

You can try something like this, i am checking for an image file extension
var str = "Hello, i would like to show this image : http://logonoid.com/images/stack-overflow-logo.gif" ;
var test = (/\.(gif|jpg|jpeg|tiff|png)$/i).test(str)
if it finds a match it will return true otherwise false
Fiddle

You can use the following to match:
(https?:[^\s]+)
Group 1 will give the list of urls.. you can replace them with '' empty string to get the new string.
See DEMO

Are you familiar with regular expressions? Because the things you ask are pretty easy:
the regex to detect an URL is
^(http|https)://
and in Javascript that would be:
str.match(^(http|https)://);
Now it is up to you to find out how to save the correct output.

Simple way could looks like that
var str = "Hello, i would like to show this image : http://logonoid.com/images/stack-overflow-logo.png" ;
console.log(str.includes(":"));
if(str.includes(":") && ( (str.includes("http") || str.includes("https")) )){
var newOutput = str.split(":");
for(var i in newOutput){
console.log("[" + i + "]: " + newOutput[i]);
}
var message= newOutput[0];
var urlImage= newOutput[1] + newOutput[2];
console.log("message: " + message +" , URL: " + urlImage);
}else{
console.log("no URL find");
}
You can use match for that "if" and it will looks better :o)

Shortest way to do it I think:
console.log(newVal.match(/\.(jpeg|jpg|png|gif)/g) != null);
if it finds a match it will return true otherwise false

Related

Search and remove a parameter with optional character from URL

I'm looking to remove a parameter from a URL with a click event. The issue is that the parameter can either have an & before it or not. So the form is either search=MYSEARCHTERM or &search=MYSEARCHTERM.
I have the following which appears to work fine for one or other but not both. I was thinking that I could have an if / else statement one of which contains something like this. (Excuse the crappy regex but I've never written it before)
var searchKeywordRegx = new RegExp(/(?:&)/ + 'search=' + searchKeyword);
$('.searchKeyword').click(function() {
$(this).remove();
var searchKeywordRegx = new RegExp('search=' + searchKeyword);
console.log(searchKeywordRegx);
document.location.href = String( document.location.href ).replace(searchKeywordRegx , "" );
});
Am I way off base here?
Use ? to make something optional in a regexp:
var searchKeywordRegx = new RegExp('&?search=' + searchKeyword);
Seems you can do this without regular expressions. If you simply remove that portion of the document location's "search":
document.location.search = document.location.search
.replace('search=' + encodeURI(searchKeyword), '');

Select first complete string matching partial string

I have a page which contains many tags with a string in them, for example 'Am I a String? Yes'.
Using JQuery, I want to get the first instance of 'Am I a String? ' and then take the Yes or No after that and store it so I can use it in a conditional.
Any ideas?
Thanks.
The code I'm going with:
function experimentThree() {
var stringBool = $('*:contains("Was it enough? ")');
console.log('stringBool = : ' + stringBool);
console.log('stringBool Object 1 = : ' + stringBool[0]);
}
Thinking if I can get the complete string in the first object I can compare that to what I expect to see.
check this out
$('body').find('*:contains("Am I a String")').each(function(index, crntNode){
var parts = $(crntNode).text().split('?');
var flag = parts[1].trim();
alert(flag);
});
for example:
var a = $('div').text().match(/Am I a String\? (Yes|No)/g)[0];
var b = a.match(/(Yes|No)/g)[0];

Probably a easy thing to do but how do I get javascript to only split if something is there, if not leave it as is

I'm using the following to get the title from a feed:
var posttitleGETcalendar = entry.title.$t;
var posttitleREMcalendar = posttitleGETcalendar.split("_");
var title = posttitleREMcalendar[0] + "<small>" + posttitleREMcalendar[1] + "</small>";
What I'm trying to do is split the titles I get after underscore and add the tag small to the part after it.
Works great when underscore is there, but it shows the word undefined after last word if underscore is not on title.
Is there a way to use
if underscore is on title, do
if not, leave it as is
Thank you.
if(/_/.test(posttitleGETcalendar)) {
// posttitleGETcalendar.indexOf('_') != -1 would do too
// do your stuff here
}
alternatively, you could use the replace method and skip the other auxilliar variables :
var title = entry.title.$t.replace('_', '<small>') + '</small>';
You can change the last line to:
var title = posttitleREMcalendar[0]
if ( posttitleREMcalendar.length > 1 )
{
title = title + "<small>" + posttitleREMcalendar[1] + "</small>";
}
This way you will only add the second part if it's present.

How can I find a specific string and replace based on character?

I'm trying to find a specific character, for example '?' and then remove all text behind the char until I hit a whitespace.
So that:
var string = '?What is going on here?';
Then the new string would be: 'is going on here';
I have been using this:
var mod_content = content.substring(content.indexOf(' ') + 1);
But this is not valid anymore, since the specific string also can be in the middle of a string also.
I haven't really tried anything but this. I have no idea at all how to do it.
use:
string = string.replace(/\?\S*\s+/g, '');
Update:
If want to remove the last ? too, then use
string = string.replace(/\?\S*\s*/g, '');
var firstBit = str.split("?");
var bityouWant = firstBit.substring(firstBit.indexOf(' ') + 1);

Regex for parsing parameters from url

I'm a total noob with regexes and although I was trying hard I cannot create proper regexes to perform the following operation :
take url and check if it has a '?' followed by number with varying amount of digits.
if the match is correct, get the number after the '?' sign
exchange this number with different one.
So let's say we have this url :
http://website.com/avatars/avatar.png?56
we take '56' and change it to '57'.
I have the following regex for searching, I'm not sure if it's proper :
\?[0-9]+
But I have no idea how to take ? away. Should I just throw it away from the string and forget about using regex here ? Then the replace part is the only one left.
Try this:
var url = "http://website.com/avatars/avatar.png?56";
var match = url.match(/\?(\d+)/);
if(match != null) {
url = url.replace(match[1], "new number");
}
Your original regex will work just fine, just add back in the ? you are taking out like so:
var newnum = 57;
url = url.replace(/\?[0-9]+/, '?'+ newnum);
I'm no regex expert but I think you can use a lookaround to ignore the '?'
(?<=?)([0-9]+)
which should give you your number in the first match
VERY dummied-down approach:
$('#parse').click(function(e){
var fromUrl = $('#from-url').val();
var newNum = parseInt($('#new-number').val(), 10);
var urlRE = /(?!\?)(\d+)$/;
if (urlRE.test(fromUrl)){
$('#result').text(fromUrl.replace(urlRE, newNum));
}else{
$('#result').text('Invalid URL');
}
});
DEMO
There are not extravagant check-sums, error-checking, etc. Fromt here, use window.location or a string containing the URL if necessary.
Broken out in to a function (demo):
// Call this to replace the last digits with a new number within a url.
function replaceNumber(url, newNumber){
// regex to find (and replace) the numbers at the end.
var urlRE = /\?\d+$/;
// make sure the url end in a question mark (?) and
// any number of digits
if (urlRE.test(url)){
// replace the ?<number> with ?<newNumber>
return url.replace(urlRE, '?'+newNumber);
}
// invalid URL (per regex) just return same result
return url;
}
alert(replaceNumber('http://website.com/avatars/avatar.png?56', 57));
You could do this without regex.
var newNum = "57";
var url = "http://website.com/avatars/avatar.png?56";
var sUrl = url.split('?');
var rUrl = sUrl[0] + "?" + newNum;
alert(rUrl);
Split the URL at the ?
This returns an array.
Add the first item in the array and the ? and the new number back together.
http://jsfiddle.net/jasongennaro/7dMur/

Categories

Resources