replace part of href between 2 words jquery - javascript

This is simple and I have done it before but can't make it work right now.
I need to change the name of the image in below href
var href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg"
$('.share, .share-2').prop('href', function () {
$(this).replace(/(picture=).*?(&)/,'$1' + imgNew + '$2');
});

Since the href string is a URL, you can take advantage of the URL object.
var imgNew = 'http://example.com/img.png';
var href = "https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg";
var url = new URL(href);
url.searchParams.set('picture', imgNew);
console.log(url.href);
Note that not all browsers are supported at this time, so you can use a polyfill.

The replace function is a method of string, so you can't call replace from $(this) because it is a jQuery object, not a string.
If you need to change the href attribute, just use this.href = ....
EDIT: As you are using jQuery.prop method you should use it as docs proposes.
$(".some-element").prop('some-prop', function(index, old_value){
// do something
return new_value;
});
Snippet updated:
var new_img = "http://my.domain.com/img/my_new_image.jpg";
var regex_img = /\bpicture=[^&]*/
$('.share, .share-2').prop('href', function (index, old_href) {
var new_href = old_href.replace(regex_img, 'picture=' + new_img);
console.log(new_href);
return new_href;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Test
<br>
Test-2

var href="https://www.facebook.com/sharer/sharer.php?
u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-
1654-45654.jpg"
href.split('/')
["https:", "", "www.facebook.com", "sharer", "sharer.php?u=http:", "",
"myurl.com", "&description='tets'&picture=http:", "", "myurl.com", "img",
"name-1654-45654.jpg"]
href.split('/').length
12
href.split('/')[11]
"name-1654-45654.jpg"

You should change your code to the following one.
href="https://www.facebook.com/sharer/sharer.php?u=http://myurl.com/&description='tets'&picture=http://myurl.com/img/name-1654-45654.jpg"
$('.share, .share-2').prop('href', function () {
$(this).replace(/\/(?=[^\/]*$)/, '/newpicturename'));
});
The last slash and following words will be replaced by the new picture name.
An example
var str = "http://one/two/three/four";
console.log(str.replace(/\/(?=[^\/]*$)/, '/newpicturename'));

Related

How can I create a link based on this format: google->someword?

I want to create links, based on a specific format.
When I type this:
google->apple
I want get get this link:
https://www.google.hu/search?q=apple
I tried this way, but unfortunately it is not working:
//Intelligent actions start
function replace(){
var str = $('.smile').html();
var re = /google->([^ \n$]+)/g;
var url = "https://www.google.hu/search?q=" + re.exec(str)[1];
}
//Intelligent actions end
Update
Based #vinayakj answer, I start create a solution for this:
//Intelligent actions start
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
//location.href = url;
}
$( document ).ready(function() {
googleSearch($('.comment-content p').text())
$( ".comment-content p" ).replaceWith( "<a href='url'>url</a>" );
});
//Intelligent actions end
And looks like replacewith function reaplce all content in
.comment-content p
with:
url
And this function it has some problem:
Reaplce all text even if dosen't find this sting in div:
google-->some word
The link is absolute incorrect becouse I get back this value everywhere:
url
What am I doing wrong?
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
location.href = url;
}
<input onchange="googleSearch(this.value)" type=text>
Here is the final solution after all your comments
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
var url = urls[parts[0]].replace("#",encodeURI(parts[1]));
return = $("<a/>",{href: url, class:parts[0]+"-search"}).text("Keresés ..."+parts[1]);
}
$(function() {
$("div.comment-content > p.smile").each(function() {
var $link = getLink($(this).text());
$(this).html($link);
});
});
Old answer
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
return urls[parts[0]].replace("#",parts[1]);
}
window.onload=function() {
document.getElementById("myForm").onsubmit=function() {
var str = document.getElementById("q").value;
var url = getUrl(str);
if (url) alert(url); // location.href=url;
return false; // cancel the submit
}
}
<form id="myForm">
<input id="q" type="text">
</form>
I found the solution, but thanks for everybody:
$("div.comment-content > p.smile").each(function(){
var original = $(this).text();
var replaced = original.replace(/google->([^.\n$]+)/gi, '<a class="google-search" href="https://www.google.hu/search?q=$1" target="_blank">Keresés a googleben erre: $1</a>' );
$(this).html(replaced);
console.log("replaced: "+replaced);
});
$("a.google-search").each( function() {
this.href = this.href.replace(/\s/g,"%20");
});

Get last part of the url

Trying to get the last part of the url in a pretty weird html structure. Don't ask why it's built that way. There is a very good reason behind it.
The html looks like this
<li class="lifilter"><input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
and the js i'm trying to use
$('#Cheeks... label a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = url.split("/");
var finalvar = urlsplit[4];
$(this).addClass(finalvar);
});
edit: damn.. i can only post once every 90 minutes.
here is updated question with updated html
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
and the js code i'm trying to use (from a previous answer)
$('.lifilter').each(function(){
$(this).find(".filtercheck").next('label').find('a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = lasturl.split("/");
console.log(urlsplit);
var finalvar = urlsplit.pop();
console.log('Adding class: ' + finalvar);
$(this).addClass(finalvar);
});
});
OK, so it appears no one here attempted to try the solution here before posting.
First things first cheeks.... This is a tricky ID to find (You have to escape the periods). The label is also not part of the internal html where ID is cheeks..., so we need to find the adjacent element and look the a anchor tag you're looking for.
Here's the code:
$(document).ready(function() {
$('#Cheeks\\.\\.\\.').next('label').find('a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = lasturl.split("/");
console.log(urlsplit);
var finalvar = urlsplit.pop();
console.log('Adding class: ' + finalvar);
$(this).addClass(finalvar);
});
});
And here is a working jsfiddle with the solution.
keeping it simple like your code you'd do
finalvar = urlsplit[urlsplit.length-1];
in case you don't want the base url as a valid return then:
finalvar = ( urlsplit.length > 1 ? urlsplit[urlsplit.length-1] : "" );
replace "" with your preferred error/default return
you could also try to find the index of the last '/' and do a substring.
try this.
FIDDLE DEMO
var URI = 'www.example.com/sub1/sub2/sub3/',
parts = URI.split('/'),
lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
//RESULT : "sub3"
You can extract the last section of a path (i.e. everything after the last /) by using a regular expression:
text.replace(/.*\//g, "")
This will remove all of the text before a slash, as well as the slash itself. You'll also notice that your selector wasn't matching any elements; you're looking for labels nested within inputs, which doesn't match the html you posted (and isn't a valid DOM structure). An appropriate selector would be .lifilter label a, since the <label> is within the <li>.
$(function() {
setTimeout(function() {
$('.lifilter label a').each(function() {
// strip everything up to and including the last forward slash
var path = $(this).attr('href').replace(/.*\//g, "");
$(this).addClass(path);
});
}, 1500);
});
a.cheeks:after {
content: " (className = 'cheeks')";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
if you want the last section of url for example activation code or id.You can try this.
var url = 'www.abc.com/code=12345',
parts = url.split('='),
lastPart = parts.pop()
//lastPart = 12345

Populate list dynamically

Using jQuery FancyList from http://jquerywidgets.com/widgets/fancy-list/
I am trying to insert a <li> through code, not by a user click action.
My issue lies in the this keyword, specifically the following lines:
$(".fancy-list-footer .add").click( function() {
$('.tab-container .user-information .first-name:last').val('').removeClass('placeholder');
$('.tab-container .user-information .last-name:last').val('').removeClass('placeholder');
fancyList($(this));
});
I would like to be able to pass a first name and last name without having to populate the textboxes - a for loop will do this.
I tried changing the fancyList(elem) function to fancyList(elem, firstName, lastName) but I couldn't seem to get the correct value for elem - I tried var elem = document.getElementByClassName('fancy-list-footer') because I thought that's what the $(this) referred to in the button click, but this didn't work either.
Codepen: http://codepen.io/anon/pen/vEYaqa?editors=101
Any help appreciated!
You can make a function like so that will add a name:
function addToFancyList(first_name, last_name) {
$('.fancy-list').find(".fancy-list-content-list:last").append("<li><div class='person'><span class = 'first'>" + first_name + "</span><span class = 'last'>" + last_name + "</span></div><div class='clear'></div></li>");
}
And simply call it like so:
$(function () {
addToFancyList('Tom', 'Someone');
});
the answer relies in the function itself. here is the implementation of fancyList from the link you send:
function fancyList(elem) {
var this_parent = elem.parents(".fancy-list");
rel = this_parent.attr("rel");
var regex = /(<([^>]+)>)/ig;
first_name = this_parent.find(".fancy-list-footer input#fancy-list-first-name").val().replace(/[<\s]/g, "").replace(/[>\s]/g, "");
last_name = this_parent.find(".fancy-list-footer input#fancy-list-last-name").val().replace(/[<\s]/g, "").replace(/[>\s]/g, "");
// more lines of code...
but it can easly change to this:
function fancyList(elem, first_name, last_name ) {
var this_parent = elem.parents(".fancy-list");
rel = this_parent.attr("rel");
var regex = /(<([^>]+)>)/ig;
first_name = first_name .replace(/[<\s]/g, "").replace(/[>\s]/g, "");
last_name = last_name.replace(/[<\s]/g, "").replace(/[>\s]/g, "");
// more lines of code...
this way the function will better suit your needs and won't force you to generate elements just to get their textual values

jQuery / JavaScript find and replace with RegEx

I have a number of pages that contain phone number in this format xxx-xxx-xxxx.
These phone numbers are not links, what I need to do it write some script that first finds these phone numbers. This is what I have got for that:
$(document).ready(function(){
var content = $(".main").text();
var phoneNumber = content.match(/\d{3}-\d{3}-\d{4}/)
alert(phoneNumber);
});
This works in so much that is captures the number, what I need to do now is replace that phone number on the page with
'' + 'originalPhoneNumber' + ''
However I am totally lost at this point. Can I use .replaceWith() in jQuery?
EDIT:
Okay I tried to modify the code to include the second attribute i wanted:
$(document).ready(function () {
var content = $(".main").html();
content = content.replace(/\d{3}-\d{3}-\d{4}/g, function(v){
return $('<a>').attr({
href: "tel:"+v,
onclick: "ga('send', 'event', 'lead', 'phone call', 'call');"
}).html(v)[0].outerHTML;
});
$('.main').html(content);
});
It is still adding the href but it is ignoring the onclick.
This will replace all matching strings in an element with a tel: link
<div class = "main">333-333-3333 444-444-4444</div>
<script type="text/javascript">
var content = $(".main").text();
content = content.replace(/\d{3}-\d{3}-\d{4}/g, function(v){
return $('<a>').attr('class', set.classname).attr('href', 'tel:'+v).html(v).wrap('<a>').parent().html();
});
$('.main').html(content);
</script>
Or more neatly implemented as :
$.fn.extend({
tel : function(def) {
var set = {
regex : /\d{3}-\d{3}-\d{4}/g,
classname : ""
}
$.extend(true, set, def);
var c = $(this).html();
c = c.replace(set.regex, function(v){
return $('<a>').attr('class', set.classname).attr('href', 'tel:'+v).html(v).wrap('<a>').parent().html();
});
$(this).html(c);
return this;
}
});
// default regex: 000-000-0000
$('.main').tel();
// default regex: 000-000-0000 <a> class of tel-link applied
$('.main').tel({ classname : "tel-link" });
// override regex: 0000-0000-000
$('.main').tel({ regex: /\d{4}-\d{4}-\d{3}/g });

exclude the first string from being appended to a character

FIDDLE Example
I'm learning how to append all the data attributes from div.query elements to a url string: http://web.com?get=
With the script I can get this result:
"http://web.com?get=|Africa|Asia|Europe"
But is there any way not to have the first one coupled with "|" so that the url should be
"http://web.com?get=Africa|Asia|Europe"
I want to get that result because either http://web.com?get=|Africa|Asia|Europe
or http://web.com?get=Africa|Asia|Europe| would be invalid. Any suggestions?
JS:
$( document ).ready(function() {
$(".query").each(function() {
var div_terms = $(this).data('term'),
source = $('#main').data('source');
var x = source+'|'+div_terms;
$('#main').data('source',x);
$('.result').html(x);
});
});
HTML:
<div id="main" data-source="http://web.com?get="></div>
<div class="query" data-term="Africa"></div>
<div class="query" data-term="Asia"></div>
<div class="query" data-term="Europe"></div>
<div class="result"></div>
The easiest way is to pull all the countries to an array and join them using the pipe character.
var terms = $('.query').map( function() {
return $(this).data('term');
}).get().join('|');
var source = $('#main').data('source');
$('.result').html( source + terms );
Demo
http://jsfiddle.net/cHtT6/3/
You just need to replace the first '|' in the resulting url with an empty character ''.
Make it simple use javascript join function
$( document ).ready(function() {
var terms=[];
$(".query").each(function() {
var div_terms = $(this).data('term');
terms.push(div_terms);
});
var x = $('#main').data('source')+terms.join("|");
$('.result').html(x);
});
Fiddle here
Use an if statement to check if it's the first 'data-term'. If it is then don't use the | character. Then in the else statement you just do as you've already done
DEMO
Just Check whether end is reached like this:
$( document ).ready(function() {
var i=0;
$(".query").each(function() {
i++;
var div_terms = i==$(".query").length? $(this).data('term')+"":$(this).data('term')+"|",
source = $('#main').data('source');
var x = source+''+div_terms;
$('#main').data('source',x);
$('.result').html(x);
});
});
Here when last term is reached. Automatically only "" is appended in all other cases "|" is appended.

Categories

Resources