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 });
Related
Trying to wrap specific keywords in hyperlinks, but replacements take place inifitely many times:
var replacements = [
{ txt: 'magicFunction', link: 'https://www.example.com/doc/api/magicFunction.htm' },
];
$(function() {
$.each(replacements,
function() {
var searchWord = this.txt;
var link = this.link;
$('body:contains("' + searchWord + '")').each(function() {
var newHtml = $(this).html().replace(searchWord,
'' + searchWord + '');
$(this).html(newHtml);
});
}
);
});
I'd need a condition around the matching part to say that if is already wrapped in a hyperlink then don't do anything, or some other workaround.
How can it be fixed?
https://jsfiddle.net/m4j28s13/
You can select all nodes in the body but exclude all <a> elements:
$('body *:not(a):contains("' + searchWord + '")').each(...)
See proof-of-concept example:
var replacements = [{
txt: 'magicFunction',
link: 'https://www.example.com/doc/api/magicFunction.htm'
}, ];
$.each(replacements,
function() {
var searchWord = this.txt;
var link = this.link;
$('body *:not(a):contains("' + searchWord + '")').each(function() {
var newHtml = $(this).html().replace(searchWord,
'' + searchWord + '');
$(this).html(newHtml);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>This sentence mentions magicFunction() in a paragraph.</p>
<p>The following code block (from API reference) mentions it too:</p>
<code class="code-block hljs lua">if a==0 then
h=magicFunction('foo')
end</code>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/highlight.min.js"></script>
Update: to handle cases where an <a> element may contain nested tags that contain the replacement word, another solution will be to actually replace :contains with a custom guard clause in the callback, which will check if the child textNodes contain the keyword. If it does, then perform the replacement:
var replacements = [{
txt: 'magicFunction',
link: 'https://www.example.com/doc/api/magicFunction.htm'
}, ];
$.each(replacements,
function() {
var searchWord = this.txt;
var link = this.link;
$('*:not(a, script)').each(function() {
const textContent = $(this).contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
}).text();
if (textContent.match(searchWord)) {
var newHtml = $(this).html().replace(searchWord,
'' + searchWord + '');
$(this).html(newHtml);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>This sentence mentions magicFunction() in a paragraph.</p>
<p>The following code block (from API reference) mentions it too:</p>
<code class="code-block hljs lua">if a==0 then
h=magicFunction('foo')
end</code>
<p>This mention is already linked (should not be linked again): <a class="postlink" href="//www.example2.com/doc/api/magicFunction"><code style="display:inline">magicFunction</code></a></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/highlight.min.js"></script>
I will post the part of a function that is adding numbers that are clicked into selected input field.
So, I need to separate it with a comma (,). I tried some of the examples but it seems not to be working on the function that I wrote.
var rowRange = 'abcdefghijklmnopqrstuvwxyz'.split('');
var $cart = $('#seats'),
$counter = $('#counter'),
sc = $('#seat-map').seatCharts({
map: [
'aaaaa__aaaaa',
'aaaaa__aaaaa'
],
naming : {
top : false,
getLabel : function (character, row, column) {
return rowRange[row - 1].toUpperCase() + column;
},
},
click: function () {
if (this.status() === 'available') {
$('#seats').split(",")
.attr('id', 'cart-item-'+this.settings.id)
.val(this.settings.label)
.appendTo($cart);
$counter.text(sc.find('selected').length+1);
return 'selected';
});
});
Seat is a input field where comma needs to be added after every click on any number.
.split(",")
when I remove this part the code works like it should, but without adding comma.
.split() doesn't work on jquery objects. Instead use it on the values in your select.
Here is an example on how it could work.
$selected = $('#selected');
$(".seat").on("click", function() {
const cur = $selected.val();
const valToInsert = $(this).text();
$selected.val(cur.length === 0 ? valToInsert : cur.split(',').concat(valToInsert).join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="selected">
<button class="seat">a</button>
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'));
How can i split the string containing <br/> tag using jquery. I tried the following code but it get error in console. I am not sure how to split the string based on <br/> tag Here is the code what i tried
jQuery(document).ready(function($)
{
var lines = jQuery('this is for testing <br/> How are you<br/>').split('<br/>');
jQuery.each(lines, function() {
alert(this);
});
});
Any suggestion would be great.
Lots of duplicate answers here. This one is different. If you can guarantee the spelling of the <br/> tag, the other answers are fine. But if you have no control over the HTML, the line break tag could come in different formats:
<br/>
<BR/>
<br />
<br>
<br >
...etc.
major browsers can all handle all of these, but only the first will be handled by the suggested .split("<br/>") operation. A more robust option is to use a regular expression to match the tag:
jQuery(document).ready(function($)
{
var brExp = /<br\s*\/?>/i;
var lines = ("this is for testing <br/> How are you<BR />").split(brExp);
});
I've written the expression to be case-insensitive, allow any number of spaces after '<br', and the '/' is optional.
You want to split a vanilla string, don't pass it to $() rather simply;
jQuery(document).ready(function($)
{
var lines = 'this is for testing <br/> How are you<br/>'.split('<br/>');
jQuery.each(lines, function() {
alert(this);
});
});
Try using this:
var exploded = lines.split('<br />');
more info here
What if you try:
jQuery(document).ready(function($)
{
var lines = 'this is for testing <br/> How are you<br/>'.split('<br/>');
each(lines, function() {
alert(this);
});
});
Can't you just do something like:
var lines = 'this is for testing <br/> How are you<br/>'.split('<br/>');
Just as a side note if you want to get rid of the empty elements you can filter the lines like so:
// this will get rid of empty elements
lines = lines.filter(function(n) {
return n;
});
jQuery(document).ready(function($)
{
var str = 'this is for testing <br/> How are you<br/>';
var lines = str .split('<br/>');
jQuery.each(lines, function() {
alert(this);
});
});
No need to wrap in jquery like :
jQuery('this is for testing <br/> How are you<br/>').split('<br/>');
Can be like :
('this is for testing <br/> How are you<br/>').split('<br/>');
DEMO
Try this
jQuery(document).ready(function($)
{
var lines = ('this is for testing <br/> How are you<br/>').split("<br/>");
jQuery.each(lines, function() {
alert(this);
});
});
Demo
Here is the Working code
jQuery(document).ready(function($)
{
var lines = 'this is for testing <br/> How are you<br/>'.split('<br/>');
alert("workig");
jQuery.each(lines, function() {
alert(this);
});
});
That's no jQuery solution, but hopefully somebody will find it useful. The function returns one or two elements.
function splitContentsOnBr(el) {
const before = document.createElement('div');
const after = document.createElement('div');
let found = false;
el.childNodes.forEach(c => {
if (found) {
after.appendChild(c.cloneNode(true));
} else if (c.tagName == 'BR') {
found = true;
} else {
before.appendChild(c.cloneNode(true));
}
});
return after.childNodes.length ? [before, after] : [before];
}
document.querySelector('#result').innerHTML = splitContentsOnBr(document.querySelector('h1'))
.map(el => el.textContent.trim())
.join(', ');
<h1>
First part
<br>
Second part
</h1>
<div id="result">
</div>
I am working on a new masterpage withing sharepoint 2010. One of the placeholders produces the sitename - the page name in a string. When the page is ready the sources shows this for exampe.
<h1 class="ribbonmc">
Devness Squared - Mark Jensen
</h1>
Devenss Squared is the site name and Mark Jensen is the page name. I am trying to remove the sitename from being displayed and show the page name only using jQuery. This is what I have so far.
$(document).ready(function() {
$('#ribbonmc').text(function(i, oldText) {
return oldText === 'Devness Squared - ' ? '' : oldText;
});
});
Regex solution:
$(".ribbonmc").text(function(i, oldText) {
return oldText.replace(/^Devness Squared - /, "");
});
Non-regex solution:
$(".ribbonmc").text(function(i, oldText) {
var r = "Devness Squared - ";
return oldText.indexOf(r) === 0 ? oldText.substring(r.length) : oldText;
});
$(document).ready(function() {
var sitename = 'Devness Squared - ';
$(".ribbonmc").text(function(i, oldText) {
return oldText.indexOf(sitename) === 0 // if it starts with `sitename`
? oldText.substring(sitename.length) // t: return everything after it
: oldText; // f: return existing
});
});