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
});
});
Related
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>
I'm using the Twitter API to get top 5 tweets for my app. I need to highlight, or link parts of the tweets differently. Ex, #'s will be orange, #'s will be red and clickable, etc...
From their API, they offer user_timeline endpoint:
https://dev.twitter.com/rest/reference/get/statuses/user_timeline
But the tweets object's text returns with those special characters embedded within it. I don't see options to pull out those #, # and href from the object:
Tweets object:
{
...
text: "This is some text #tagName that I'd like to #parse here https://t.co/m9Addr4IlS",
...
}
While I can write my own string parser to look for those things, is there something the Twitter API offers to handle this?
EDIT: <tweets> is an Angular directive that ng-repeats over my tweets from ModulesService. replace doesn't seem to be appending the DOM tags
scope.getTweets = function() {
ModulesService.getTweets().success(function(res) {
if (res && Array.isArray(res)) {
scope.tweets = parseTweets(res);
}
});
};
scope.getTweets();
var parseTweets = function (tweets) {
tweets.forEach(function (tweet) {
tweet.text.replace(/(#[^ ]+)/g, '<a class="user">$1</a>').
replace(/(#[^ ]+)/g, '<span class="hash">$1</span>').
replace(/(https?:\/\/[^ ]+)/g, '$1');
console.log('tweet!', tweet.text); //does not contain altered HTML
});
return tweets;
};
HTML:
<div ng-repeat="tweet in tweets" class="post-body clearfix">
{{tweet.text}}
</div>
recommended solution
The library twitter-text does the work for you.
As per their examples:
autolink
var twitter = require('twitter-text')
twitter.autoLink(twitter.htmlEscape('#hello < #world >'))
extract entities
var usernames = twttr.txt.extractMentions("Mentioning #twitter and #jack")
// usernames == ["twitter", "jack"]
Using that solution will save you from re-inventing the wheel and will provide you with a stable working code :)
alternative
Inside the tweet object that you receive from the user_timeline API endpoint, the entities property stores the list of urls, hashtags and mentions included inside the tweet. These contain the text content as well as the position (start / end character indices) of each entity.
Example hashtag entity:
"entities": {
"hashtags": [
"text": "pleaseRT"
"indices": [
6,
13
]
]
cf Entities documentation for more info.
Try:
var text = "This is some text #tagName that I'd like to #parse here https://t.co/m9Addr4IlS";
var div = document.getElementsByTagName('div')[0];
div.innerHTML = text.replace(/(#[^ ]+)/g, '<a class="user">$1</a>').
replace(/(#[^ ]+)/g, '<span class="hash">$1</span>').
replace(/(https?:\/\/[^ ]+)/g, '$1');
.hash { color: orange; }
.user { color: red; }
<div></div>
Loop over the returned tweets and modify the tweet text according to some conditions:
returnValues.forEach(function (tweet) {
if (tweet.text.search(/#|#/ig) > -1) {
var words = obj.text.split(' ');
var parsedTweetText = words.map(function (word) {
if (word.indexOf('#') === 0)
return '<span class="hashtag">' + word + '</span>';
else if (word.indexOf('#') === 0)
return '<span class="at-user">' + word + '</span>';
else
return word;
}).join(' ');
tweet.text = parsedTweetText;
}
});
I have this sample code for replacing text with emoticons when message is submitted. However, I want to add title on emoticons when mouse hover to it to identify what kind of emoticon user used, how can I achieved that in my current code? thanks
<html>
<head>
<title>Testing Emoticon</title>
</head>
<body>
<input type="text" name="message" id="message">
<br><br>
<div class="results"></div>
<script language="javascript" src="./assets/js/jquery-1.11.3.min.js"></script>
<script>
function replaceEmoticons(text) {
var emoticons = {
':-)' : 'smile.png',
':)' : 'smile.png',
';)' : 'wink.png',
';-)' : 'wink.png',
':P' : 'tongue.png'
}, url = "http://localhost/cb/2/assets/img/smileys/", patterns = [],
metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;
// build a regex pattern for each defined property
for (var i in emoticons) {
if (emoticons.hasOwnProperty(i)){ // escape metacharacters
patterns.push('('+i.replace(metachars, "\\$&")+')');
}
}
// build the regular expression and replace
return text.replace(new RegExp(patterns.join('|'),'g'), function(match) {
return typeof emoticons[match] != 'undefined' ?
'<img src="'+url+emoticons[match]+'"/>' :
match;
});
}
</script>
<script>
$('#message').keypress(function(e){
if(e.which == 13){//Enter key pressed
e.preventDefault();
var emoticon = $('#message').val();
$('.results').html(replaceEmoticons(emoticon));
}
});
</script>
</body>
</html>
Main purpose is solved, when you type :) the output title on hover is smile that came from smile.png thanks to #PraveenKumar
Additional question is can I customize the title, like if I type :P the output of title might be Stick Out Tongue instead of tongue that came from tongue.png ?
For my additional question, I came up with a solution base on my research and trial error tests.
I've got an idea when I see this link javascript emotify by Ben Alman.
So I reconstruct my codes and came up to this:
I modified my json array to add more data.
var emoticons = {
':-)' : ['smile.png', 'Smile'],
':)' : ['smile.png', 'Smile'],
';)' : ['wink.png', 'Wink'],
';-)' : ['wink.png', 'Wink'],
':P' : ['tongue.png', 'Stick Out Tongue']
}, url = "http://localhost/cb/2/assets/img/smileys/", patterns = [],
metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g;
And also this part of the function to match my new json array:
// build the regular expression and replace
return text.replace(new RegExp(patterns.join('|'),'g'), function (match) {
return typeof emoticons[match][0] != 'undefined' ?
'<img src="'+url+emoticons[match][0]+'" title="' + emoticons[match][1] + '" />' :
match;
});
Now its really working according to my needs. Hooray!
Add it while replacing:
return text.replace(new RegExp(patterns.join('|'),'g'), function(match) {
return typeof emoticons[match] != 'undefined' ?
'<img src="'+url+emoticons[match]+'" title="' + emoticons[match].substr(0, emoticons[match].length-4) + '" />' :
match;
});
Working Bin: http://jsbin.com/cotefuwate/edit?output
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 });
I need to replace some part of text, e.g. mustache var {{myvar}}, on already loaded page.
Example html:
<html>
<head>
<title>{{MYTITLE}}</title>
</head>
<body>
<p><strong><ul><li>text {{TEXT}}</li></ul></strong></p>
{{ANOTHER}}
</body>
</html>
What's the problem? Use $(html).html(myrenderscript($(html).html()))!
It's ugly, slow and brokes <script> tags.
What do you want?
I want to get closest tag with {{}} and than render and replace.
Your researches?
Firstly, i tried: $('html :contains("{{")). But it returns <title>, <p>, <strong> .... But i need <title> and <li>.
Than i tried to filter them:
$('html :contains("{{")').filter(function (i) {
return $(this).find(':contains("{{")').length === 0
});
...but it WONT return {{ANOTHER}}. And that is my dead end. Your suggestions?
Using http://benalman.com/projects/jquery-replacetext-plugin/ you could do the following:
$('html *').replaceText(/{{([^}]+)}}/, function(fullMatch, key) {
return key;
}, true);
See http://jsfiddle.net/4nvNy/
If all you want to do is replace that text - then surely the following works (or have I mis-understood)
usage is as follows: CONTAINER (body) - replaceTExt (search term (I have built the function to always include {{}} around the term), (replace - this will remove the {{}} as well)
$('body').replaceText("MYTITLE","WHATEVER YOU WANT IT REPLACING WITH");
$.fn.replaceText = function(search, replace, text_only) {
return this.each(function(){
var v1, v2, rem = [];
$(this).find("*").andSelf().contents().each(function(){
if(this.nodeType === 3) {
v1 = this.nodeValue;
v2 = v1.replace("{{" + search + "}}", replace );
if(v1!=v2) {
if(!text_only && /<.*>/.test(v2)) {
$(this).before( v2 );
rem.push(this);
}
else this.nodeValue = v2;
}
}
});
if(rem.length) $(rem).remove();
});
};
You could avoid jQuery altogether if you wanted to with something like this:
<body>
<p><strong>
<ul>
<li>text {{TEXT}}</li>
</ul>
</strong></p>
{{ANOTHER}}
<hr/>
<div id="showResult"></div>
<script>
var body = document.getElementsByTagName('body')[0].innerHTML;
var startIdx = 0, endIdx = 0, replaceArray = [];
var scriptPos = body.indexOf('<script');
while (startIdx != 1) {
startIdx = body.indexOf('{{', endIdx) + 2;
if(startIdx > scriptPos){
break;
}
endIdx = body.indexOf('}}', startIdx);
var keyText = body.substring(startIdx, endIdx);
replaceArray.push({"keyText": keyText, 'startIdx': startIdx, 'endIdx': endIdx});
}
document.getElementById("showResult").innerHTML = JSON.stringify(replaceArray);
</script>
</body>
You can then do what you want with the replaceArray.