Using jQuery I need to replace spaces inside href with hyphens - javascript

I have a list of links that direct to a page which corresponds to each of the 50 states in the US.
I am looping through each states in an array and adding it the href for each but for states that contain two words I need to replaces the space (' ') between them with a hyphen('-').
example: New York must be replaced with New-York.
<a href="http://www.projectknow.com/find/New York/" class="spaces">
MUST BE REPLACED WITH
<a href="http://www.projectknow.com/find/New-York/" class="spaces">
This is what I got so far but it does NOT work. Still new to jQuery and any help would be greatly appreciated.
var option = '';
for (var i = 0; i < states.length;i++){
option += '<li><a href="http://www.states.com/find/'+ states[i] +'/"
class="spaces">'+ states[i] +'</a></li>';
}
$('.menu').append(option);
$("a.spaces").each(function (){
$(this).attr('href', $(this).attr("href").replace("","-"));
});

Use this code instead:
$(this).attr('href', $(this).attr("href").replace(/\s/g, "-");

Maybe you can replace it before add it to a link tag then you don't need to handle it after added, like this way:
var option = '';
for (var i = 0; i < states.length;i++){
var state = states[i].replace(/ /g, '-');
option += '<li>'+ states[i] +'</li>';
}

var states = [ 'New York', 'New Jersey', 'New Mexico' ];
$('.menu').append(states.map(function(state){
return '<li>'+ state +'</li>';
}).join(''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu"></ul>

You're so close!
Problem:
$(this).attr('href', $(this).attr("href").replace("","-"));
because "" != " "
Answer:
$(this).attr('href', $(this).attr("href").replace(" ","-"));
but replace only replaces the first occurrence. We could suggest regex, but as you stated you're still trying to figure things out; regex would just confuse you at this time
function replaceAll(str, find, replace) {
str = str.replace(find, replace);
if(str.indexOf(find) > -1) {
return replaceAll(str, find, replace);
}
return str;
}
and then $(this).attr('href', replaceAll($(this).attr('href'), ' ', '+'));

Related

How to add a class for texts between specific characters?

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>');
});

jQuery : passing concatenated id into selector weired situation

I am using jQuery DatePicker to select elements with '#', everything is working fine when i put "direct" string in the selector, but once i begin concatenating, the result is very suspicious.
Maybe this console screenshot explain what i am struggling with
HTML :
<input id="wizard:wizard-body:datePiece_picker" name="wizard:wizard-body:datePiece_picker" type="text" value="">
Javascript :
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, "g"), replace);
}
var TYPEDIALOG = "wizard:wizard-body:";
var id = replaceAll(TYPEDIALOG, ":", "\\\\:")+ "datePiece_picker";
if ($("#" + id).length != 0) {
$("#" + id).datepicker({
dateFormat : "dd/mm/yy"
});
}
Your replace was adding too many backslashes:
http://jsfiddle.net/BaypN/
var id = replaceAll(TYPEDIALOG, ":", "\\:") + "datePiece_picker";
As a side note, this is probably a pretty good argument for avoiding : in element ids. Also, datePiece_picker could be a class instead of part of the id.

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/

JavaScript, the use replace

var text_source="<a href='c:/exam_file.xls' target='_blank'>file downdload</a>";
text_search="file";
text_source.replace(new RegExp(text_search, 'gi'),
"<span style='font-weight:bold'>" +
text.toLowerCase() + "</span>");
The "a tag" link address has also changed:
<span style='font-weight:bold'>file</span> download
But, It should look like this. I have to change the text value in the "a tag".
<span style='font-weight:bold'>file</span> download
I will address what I said in a second, but you can do this without a loop with just pure regex. Below is how I accomplished this:
var text_source = "<a href='c:/bilmem_ne_dosyasi.xls' target='_blank'>Dosya Downdload</a>";
text_search = "dosya";
var patt = new RegExp("(<a .*?>)(" + text_search + ")(.*?</a>)","gi");
var text_source = text_source.replace(patt, function(match, $1, $2, $3) {
return $1 + "<span style='font-weight:bold'>" + $2.toLowerCase() + "</span>" + $3;
});
document.write(text_source);
DEMO
​
Getting back to what I said earlier, however, html can be a very, very complex language, and although regex can be used to parse it, partially, it should not be used for large quantities of data. Some patterns are too intricate to match against.
To ensure that your RegExp runs only against the content of the elements, you will need to select all of the elements that you want to manipulate and check their contents.
As an example:
var regExp = /dosya/ig;
[].slice.call(document.getElementsByTagName('a'), 0).forEach(function(element) {
if(regExp.test(element.textContent)) {
element.innerHTML = element.textContent.replace(regExp, function(text) {
return '<span style="font-weight: bold">' + text.toLowerCase() + '</span>';
})
}
});
There is also a jQuery pseudo selector :contains that does a similar thing.
Whilst the replies about not using regexes with HTML or XML are on the whole, correct, you could use the following for simple cases where you don't have too many nested tags:
var text_source="<a href='c:/bilmem_ne_dosyasi.xls' target='_blank'>Dosya Downdload</a>";
text_search="(<[^>]*>[^<]*)(dosya)([^<]*<[^>]*>)";
var replaced = text_source.replace(new RegExp(text_search, 'gi'), "$1<span style='font-weight:bold'>$2</span>$3");

Categories