jQuery : passing concatenated id into selector weired situation - javascript

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.

Related

Using jQuery I need to replace spaces inside href with hyphens

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'), ' ', '+'));

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/

Extract text from a ajax response which contains <tag>

I have write a little piece of code to retrieve news from rss page. Here is the code :
this.loadRecentNews = function loadRecentNews() {
$.get("http://rss.nytimes.com/services/xml/rss/nyt/GlobalHome.xml", function (data) {
$(data).find("item").each(function () {
var el = $(this);
console.log("------------------------");
console.log("Title : " + el.find("title").text());
console.log("Link : " + el.find("link").text());
console.log("Description: " + el.find("description").text());
console.log("Date: " + el.find("pubDate").text());
});
});
};
Here is the output :
Title : Example of title
Link : http://www.example.com
Description : Example of <<bb>>Description</b> containing <> tag..
Date : Example of date
My problem is that i want to extract only the text of the Description value to build a new Json object which contain this text.
How can i do to extract only the text without <> values ?
Seeing as you're using jQuery, you can use its .text() method.
var beforeText = "Example of <b>Description</b>" ;
var afterText = $("<p>").html(beforeText).text() ;
This uses jQuery to make a new HTML element (that is never added to the page) and update its innerHTML and then use .text() to get the text only.
Another (riskier) option is a regex to replace anything between < and > with an empty string:
var afterText = beforeText.replace(/<[^>]*>+/g, "")

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");

How would I remove from spaces from a search form using jQuery?

I've replaced the submit URL from the search form with this jQuery snippet:
<script type="text/javascript">
$(document).ready(function() {
$('.search-form').submit(function() {
window.location.href = "/search-" + $('.search-form input:text').val() + "-" + "keyword"+ "-"+ "keyword2/" + $('.search-form input:text').val() + ".html";
return false;
});
});
</script>
This works fine and turns the URL into a nice SEO cleaned URL. But how can I replace the spaces?
When someone types in "search me" the URL looks like /search-search me-keyword-keyword2/search me.html with spaces. With + or - it would look much better. I know of str_replace from PHP, but how would I go about this in jQuery?
There's a native JavaScript function called encodeURIComponent that's intended to do exactly what you need.
window.location.href =
"/search-" +
encodeURIComponent($('.search-form input:text').val()) +
"-" + "keyword" + "-" + "keyword2/" +
encodeURIComponent($('.search-form input:text').val()) +
".html";
Method 1: Using Replace
<script type="text/javascript">
$(document).ready(function() {
$('.search-form').submit(function() {
var value = $('.search-form input:text').val();
value = value.replace(' ', ''); // replace
window.location.href = "/search-" + value + "-" + "keyword"+ "-"+ "keyword2/" + value + ".html";
return false;
});
});
</script>
Method 2: Encoding URL
<script type="text/javascript">
$(document).ready(function() {
$('.search-form').submit(function() {
// encode url
var value = encodeURIComponent($('.search-form input:text').val());
window.location.href = "/search-" + value + "-" + "keyword"+ "-"+ "keyword2/" + value + ".html";
return false;
});
});
</script>
Note that replace method would work even in JQuery because Jquery is simply library of javascript :)
http://www.w3schools.com/jsref/jsref_replace.asp
replace() method is native javascript. That'll get you what you want.
You could remove spaces with using mod_rewrite. It’s quite useful way. You can also remove spaces from URLs by replacing spaces by %20, but that only helps with spaces and won't escape other characters. What you really need to do is use a URL-escaping function.

Categories