How to add a class for texts between specific characters? - javascript

I'm writing my own blog using Blogger. I want to mark some prominent words. For example, when I write *Red* in an editor. It should automatically add a key class and wrap it with the span tag. So, the final result should be as following:
<span class="key">Red</span>
Now, I am trying to write a JQuery script but it still doesn't work properly.
$markText = $('span').filter(function(){
$t = $(this).text();
return $t.charAt(0) === "*" && $t.charAt(4) === "*"}).each(function() {
$s1 = $t.slice(1,4);
$s2 = $t.slice(5);
$(this).replaceWith('<span class="key">' + $s1+ '</span>' + '<span>'+$s2+'</span>');
});
Please see the demo on jsFiddle

Your code can be fixed by what RaymondM has suggested, but you could try something like this as well:
$markText = $('span').each(function (i, e) {
$e = $(e);
while ($(e).text().indexOf('*') != -1) {
$e.html($e.html().replace('*', '<span class="key">').replace('*', '</span>'));
}
});
This makes use of the fact that the replace method only modifies the first occurrence of the target string.
DEMO

The $t in side the each function should be replaced by $(this).text()
$markText = $('span').filter(function(){
$t = $(this).text();
return $t.charAt(0) === "*" && $t.charAt(4) === "*"}).each(function() {
$s1 = $(this).text().slice(1,4);
$s2 = $(this).text().slice(5);
$(this).replaceWith('<span class="key">' + $s1+ '</span>' + '<span>'+$s2+'</span>');
});

Related

Generating a string of jQuery for Ajax uploading

My page generates a jQuery string (the jqueryBlock below) that gets ajaxed up to a php file that writes it into a new html file, where it will execute. The code "A" below is what I have now to generate the final jQuery, "B" below in the new html file.
"A"
var targetName = "redbox";
target = $('div[filename=' + targetName + ']').hide()[0];
var jqueryBlock= '<script>$(function() {\n';
jqueryBlock += "$('#" + this.id + "').click(function() {\n";
jqueryBlock += "$('#" + target.id + "').show();\n";
jqueryBlock += "}).css('cursor', 'pointer');\n";
jqueryBlock += "$('#" + target.id + "').dblclick(function(){\n$(this).hide();\n});\n";
jqueryBlock += "})<\/script>";
"B"
<script>$(function() {
$('#T_1376594221987').click(function() {
$('#T_1376594237267').show();
})
.css('cursor', 'pointer');
$('#T_1376594237267').dblclick(function(){
$(this).hide();
});
})</script>
This all works, but it's a nightmare to write block A, trying to keep track of the multiple levels of quotes and all the parens and braces and not being able to break lines to make them more readable. I'm thinking that there must be a way to do this where I can write something that looks more like the finished jQuery for "A". Can anyone suggest a better method?
Thanks.
Ok, well... I came up with some ideas... you may like some, all, or none of it. But I figured I'd paste it here. Just a couple of techniques. You can view the JsFiddle as well.
The first, make a function for creating the jQuery selector. This way you can just pass the id, and get your selector, no quotes to worry about.
function makeJqIdSelector(id) {
return "$('#" + id + "')";
}
The same way of thinking, you could write functions to wrap something in <script> tags (or even a function.
function wrapScriptTags(scr) {
return "<script>\n" + scr + "\n<\/script>";
}
Finally, you can use an array to join the elements so you don't have to keep typing out \ns. ie:
var arr = [];
arr.push("a",
"b",
"c"
);
var str = arr.join("\n");
//output:
//a
//b
//c
This has the added effect of being more efficient as well. (probably not an issue for modern browsers, and especially not for this few strings)
Here it is all together:
var thisSelect = makeJqIdSelector(this.id);
var targetSelect = makeJqIdSelector(target.attr('id'));
var jblock = [];
jblock.push(
"$(function() {",
thisSelect + ".click(function() {",
targetSelect + ".show();",
"}).css('cursor', 'pointer');",
targetSelect + ".dblclick(function(){\n$(this).hide();",
"});",
"});"
);
var jqueryBlock = wrapScriptTags(jblock.join("\n"));
output
<script>
$(function() {
$('#T_1376594221987').click(function() {
$('#T_1376594237267').show();
}).css('cursor', 'pointer');
$('#T_1376594237267').dblclick(function(){
$(this).hide();
});
});
</script>
Note: Obviously, I did not spend a lot of time making sure the output was perfect. It was just for the technique - I have no real way of testing it.
If I understanded everything, you could ajax up only the dynamic variables to the PHP file, and change it to something like this:
<script>$(function() {
$('#<?php echo $_GET['id']; ?>').click(function() {
$('#<?php echo $_GET['id']; ?>').show();
})
.css('cursor', 'pointer');
$('#<?php echo $_GET['id']; ?>').dblclick(function(){
$(this).hide();
});
})</script>
In coffeescript you can use a text block that keeps track of the indention level for you. Maybe you can change to coffeescript just for this script.
http://coffeescript.org/#strings

Make word in into a link jQuery

I'm trying to make this:
<td class="Monthly Status-cell">/fileid=XXXX</td>
Display as
http://www.domain.com/fileid=XXXX
Can you tell me what is wrong with my code?
$('.Status-cell').replaceWith(function() {
var url = $.trim($(this).text());
return '' + url + '';
});
Thanks!
Use .html() instead of .replaceWith(). While using replaceWith you are replacing the td with anchor inside your table, which is invalid and that must be causing your alignment to get messed up.
$('.Status-cell').html(function(_, currentText) {
var url = "http://www.domain.com" + $.trim(currentText);
return '' + url + '';
});
Fiddle
Rather than replace the td with a link you should place the link in the td. Also you didn't add the domain to the link
$('.Status-cell').html(function() {
var url = window.location.protocol+'//'+window.location.host+$.trim($(this).text());
return '' + url + '';
});
http://jsfiddle.net/bUpYE/1/
Try
$('.Status-cell').html(function(idx, value){
value = $.trim(value);
return 'http://www.domain.com' + value + '';
})
Demo: Fiddle
Place the link in the cell using .html() instead of .replaceWith():
var domain = window.location.hostname; // current domain
$('.Status-cell').html(function(i, value) {
var link = domain + $.trim(value);
return '' + link + '';
});
http://jsfiddle.net/samliew/ZUYCX/

Javascript - Regex : How to replace id in string with the same id plus number?

I have a string with multiple elements with id's like below:
var data = "<div id='1'></div><input type='text' id='2'/>";
Now I'm using this regex to find all the id's in the string:
var reg = /id="([^"]+)"/g;
Afterwards I want to replace all those id's with a new id. Something like this:
data = data.replace(reg, + 'id="' + reg2 + '_' + numCompare + '"');
I want reg2, as seen above, to return the value of the id's.
I'm not too familiar with Regular Expressions, so how can I go about doing this?
Instead of using regex, parse it and loop through elements. Try:
var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
numCompare = 23,
div = document.createElement("div"),
i, cur;
div.innerHTML = data;
function updateId(parent) {
var children = parent.children;
for (i = 0; i < children.length; i++) {
cur = children[i];
if (cur.nodeType === 1 && cur.id) {
cur.id = cur.id + "_" + numCompare;
}
updateId(cur);
}
}
updateId(div);
DEMO: http://jsfiddle.net/RbuaG/3/
This checks to see if the id is set in the first place, and only then will it modify it.
Also, it is safe in case the HTML contains a comment node (where IE 6-8 does include comment nodes in .children).
Also, it walks through all children of all elements. In your example, you only had one level of elements (no nested). But in my fiddle, I nest the <input /> and it is still modified.
To get the get the updated HTML, use div.innerHTML.
With jQuery, you can try:
var data = "<div id='1'></div><div id='asdf'><input type='text' id='2'/></div>",
numCompare = 23,
div = $("<div>"),
i, cur;
div.append(data);
div.find("[id]").each(function () {
$(this).attr("id", function (index, attr) {
return attr + "_" + numCompare;
});
});
DEMO: http://jsfiddle.net/tXFwh/5/
While it's valid to have the id start with and/or be a number, you should change the id of the elements to be a normal identifier.
References:
.children: https://developer.mozilla.org/en-US/docs/DOM/Element.children
.nodeType: https://developer.mozilla.org/en-US/docs/DOM/Node.nodeType
jQuery.find(): http://api.jquery.com/find/
jQuery.attr(): http://api.jquery.com/attr/
jQuery.each(): http://api.jquery.com/each/
Try using
.replace(/id='(.*?)'/g, 'id="$1_' + numCompare + '"');
Regex probably isn't the right way to do this, here is an example that uses jQuery:
var htmlstring = "<div id='1'></div><input type='text' id='2'/>";
var $dom = $('<div>').html(htmlstring);
$('[id]', $dom).each(function() {
$(this).attr('id', $(this).attr('id') + '_' + numCompare);
});
htmlstring = $dom.html();
Example: http://jsfiddle.net/fYb3U/
Using jQuery (further to your commments).
var data = "<div id='1'></div><input type='text' id='2'/>";
var output = $("<div></div>").html(data); // Convert string to jQuery object
output.find("[id]").each(function() { // Select all elements with an ID
var target = $(this);
var id = target.attr("id"); // Get the ID
target.attr("id", id + "_" + numCompare); // Set the id
});
console.log(output.html());
This is much better than using regex on HTML (Using regular expressions to parse HTML: why not?), is faster (although can be further improved by having a more direct selector than $("[id]") such as giving the elements a class).
Fiddle: http://jsfiddle.net/georeith/E6Hn7/10/

jQuery Replace character and symbol in string in each div , comma by € and € by nothing

so here is the scenario:
I have a bunch of spans with a class of " price " like that : 12,99€
I needed to split the cents after the coma so I could style it with css -> that's done , cents got its own class " cents "
Now I'm trying to replace the coma "," by the € euro symbol, and remove the € symbol at the end 'replace it with nothing, empty)
I hope it makes sense, here is an example...:
How it is now: 12,99€
and
What I need: 12€99
My code right now:
<!-- the html part CANNOT BE MODIFIED -->
<span class="price">29,49€</span>
<script>
jQuery(".price").each(function() {
var newText = jQuery(this).text().split(",").join("</span>,<sup class='cents'>");
newText = "<span class='euros'>" + newText + "</sup>";
jQuery(this).html(newText);
});
// Tryed to replace euro symbol by nothing but doesn't work //
var value = jQuery(".cents").val()+"";
value.replace("€", "");
var val = jQuery(".cents").val();
</script>
I would definitely appreciate if someone could help me out here since I really want to learn how to achieve this. It doesn't look too complicated but can't make it work which is frustating.
$(".price").text( function(i, oldtext){
return oldtext.replace("€","").replace(",","€")
});
http://jsfiddle.net/8da54/9/
How about using the following instead:
$(".price").html(function(i, val) {
val = val.split(",");
return "<span class='euros'>" + val[0] + "</span>" + "€" +
"<sup class='cents'>" + val[1].replace("€", "") + "</sup>";
});
DEMO: http://jsfiddle.net/8da54/11/
You don't need to use replace, you can use slice or substr.
$(".price").html(function(i, oldVal) {
var value = oldVal.split(",");
return "<span class='euros'>" + value[0] + "€</span>" +
"<sup class='cents'>" + value[1].slice(0, -1) + "</sup>";
});
demo

add parameter to links on page using jquery

How do I add let's say something like ajax=1 to all links on my page with jquery. I will also need to check if the url has existing parameters. for example http://example.com/index.php?pl=132 will have to become http://example.com/index.php?pl=132&ajax=1
Also, if the link does not have any parameters, for example http://example.com/index.php, it will become http://example.com/index.php?ajax=1 I want to load the jQuery script on document ready so all links are changed on page load.
You could do something like this:
$(function() {
$("a").attr('href', function(i, h) {
return h + (h.indexOf('?') != -1 ? "&ajax=1" : "?ajax=1");
});
});
On document.ready this looks at every <a>, looks at it's href, if it contains ? already it appends &ajax=1 if it doesn't, it appends ?ajax=1.
Like this:
$(function() {
$('a[href]').attr('href', function(index, href) {
var param = "key=value";
if (href.charAt(href.length - 1) === '?') //Very unlikely
return href + param;
else if (href.indexOf('?') > 0)
return href + '&' + param;
else
return href + '?' + param;
});
})
Here is a solution I put together for native Javascript, it supports existing query strings and anchors:
function addToQueryString(url, key, value) {
var query = url.indexOf('?');
var anchor = url.indexOf('#');
if (query == url.length - 1) {
// Strip any ? on the end of the URL
url = url.substring(0, query);
query = -1;
}
return (anchor > 0 ? url.substring(0, anchor) : url)
+ (query > 0 ? "&" + key + "=" + value : "?" + key + "=" + value)
+ (anchor > 0 ? url.substring(anchor) : "");
}
I've posted my existing tests on JSBin: http://jsbin.com/otapem/2/
If you're interested in plugins, there's the jQuery Query String Object. This will allow you simple checking of parameters in the querystring, and if necessary the ability to add more, remove some, or edit others.
Taking what is above, this is the best way to concatenate parameters to links.
Also avoid link with href like href="Javascript:YourFunction();"
$(function(){
var myRandom = getRandom();
$('a[href]').each(function(i){
var currHref = $(this).attr("href");
var isAfunction = currHref.substring(0,10);
if(isAfunction == "javascript"){
$(this).attr("href",currHref);
}else{
if (currHref.charAt(currHref.length - 1) === '?')
$(this).attr("href",currHref);
else if (currHref.indexOf('?') > 0)
$(this).attr("href",currHref+"&rand="+getRandom());
else
$(this).attr("href",currHref+"?rand="+getRandom());
}
});
});
function getRandom(){
var randomnumber = Math.floor(Math.random()*10000);
return randomnumber;
}
a href must be full and corrected URL.
$(function() {
$('a[href]').attr('href', function(index, href) {
var url = new URL(href);
url.searchParams.set('ajax',1);
return url;
});
})
JSFiddle

Categories