How to "Quote" a String in jQuery? - javascript

Info's: I have some javascript code that i will show below, who i'm having problem with quotes.
html = [];
style = 'class=odd';
html.push('<li '+style+' onclick=SelectItem("'+ele.id+'","'+idItem+'","'+dsItem+'","'+qtItem+'"); >'+id+' - '+$iObjItensListaVenda.result.ds_item[i]+'</li>');
I have strings that i get from a JSON Object, as you see above.
Problem: But when i'm trying to place it as a Function Parameter on the onClick event of the <li> element, my resulting html <li> element becomes totally unformatted like that:
<li natural,"150");="" white="" american="" onclick="SelectItem("descItem1","2",TELHA" class="odd">00002 - TELHA AMERICAN WHITE NATURAL</li>
What do i want: i need a solution like a function, maybe already exists in jQuery, to Quote my String. Like a QuoteStr("s t r i n g"); to become ""s t r i n g"".
Maybe you're complaining about:
The variable ele is a html <input> element.
The variable idItem contains only numbers, they come from a JSON Object.
The variable dsItem its a string containing Item Description, it comes from the JSON Object too.
The variable qtItem contains only numbers, it is the quantity of the items, it comes from the JSON too.

The sane solution would be to use jQuery to build the element and bind the event handler, not building an HTML string:
var $li = $('<li />', {
"class": "odd",
on: {
click: function() {
SelectItem(ele.id, idItem, dsItem, qtItem);
}
},
text: id + ' - ' + $iObjItensListaVenda.result.ds_item[i]
});
If you are doing this in a loop and the variables end up having the wrong values, please see JavaScript closure inside loops – simple practical example. Alternative you could use jQuery's .data API to set and get those values.

Try \" instead of ' in onClick
$(".container").append("Edit");

You can use quotes in a string by escaping them with a backslash.
var text = "s t r i n g";
"\"" + text + "\"" === "\"s t r i n g\"";
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

You can always use backslash to escape quotes:
console.log('te\'st'); // te'st
console.log("te\"st"); // te"st
You can do the same thing for your string, but I'd suggest you rewrite the whole thing into something more usable. By that I mean not using strings to build objects, but building objects directly.
For example:
var li = document.createElement('li');
li.className = myClass;
li.onclick = function(){/*...*/};
It gets even easier with jQuery.

Related

Javascript - regex replace string [duplicate]

I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;

how to force jquery attr() to add the attribute with single quotes

I create an in memory div:
var video_div = document.createElement('div');
video_div.className = "vidinfo-inline";
In essence I have some variables:
var key = "data-video-srcs";
var value = '{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}';
And I use jquery to add that data attribute to the div:
$(video_div).attr(key, value);
Here is my problem. After doing that I get this:
<div class="vidinfo-inline" data-video-srcs="{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}"></div>
And that doesn't work putting that json in there. It has to be in single quotes. It has to look like this:
<div class="vidinfo-inline" data-video-srcs='{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}'></div>
As later on I do something like this:
var video_srcs = $('.vidinfo-inline').data('video-srcs');
And that won't work unless the json is in single quotes.
Does anyone have any ideas?
EDIT:
According to jquery: http://api.jquery.com/data/#data-html5
When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.
Thus I can't escape the double quotes, it has to be inside single quotes. I have a work around and I'll post that as an answer unless someone else has a better answer.
I have a workaround. And if anyone has a better solution, I'd love to see it.
I wrote a replace method:
var fixJson = function(str) {
return String(str)
.replace(/"{/g, "'{")
.replace(/}"/g, "}'");
};
So basically I send the html into this function and insert it into the DOM.
For example:
var html = htmlUnescape($('#temp_container').html());
html = fixJson(html);
I realize that has some code smell to it. I mean, going through everything on that element just to fix the double quotes to single quotes stinks. But for lack of other options or ideas, it works. :\
Replace the double quotes with HTML entities:
var value = '{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}';
# Naive approach:
value = value.replace('&', '&').replace('"', '"');
# Using jQuery:
var $tmp = jQuery('<div></div>');
value = $tmp.text(value).html();
// Then store it as normal

Create Regex from a string variable in javascript

var tags=["div","span","body"];
for (i=0; i<=tags.length; i++){
source = source.replace(/\&lt\;<tags[i]/i, '<span class="tags[i]"><tags[i]</span>');
}
Basically, I'm trying to put all the opening div,span and body tags around a span with a class set accordingly. But, I am having issues getting the variables inside there.
I can put lines and lines for each different tag but considering this function is called on every key press I want to keep the code as small and efficient as possible.
Or are there other alternatives? I mean it would be even better if something along these lines was possible:
source = source.replace(/\&lt\;<div|<span/i, '<span class="div|span"><div|span</span>');
But, it clearly does not get me anywhere.
You can construct your regex from a string using the RegExp object:
source = source.replace(new RegExp("\\&lt\\;<" + tags[i], "i"), '<span class="' + tags[i] + '"><' + tags[i] + '</span>');
But your idea for an alternative is also possible by capturing the tag and referencing it in the replacement:
source = source.replace(/\&lt\;<(div|span|body)/i, '<span class="$1"><$1</span>');
You can use regexes with | (equivalent of OR): () are used to get the matched elements (div, span or body), and you can get them with $1
source.replace(/<(div|span|body)/i,'<span class="$1"><$1></span>')

Select text string before comma, set it to uppercase

JS Fiddle Example
OK--I have a field that is a full name (last name, first name). The data that is returning isn't last and first name, it is full name. It is then printed last, first. I want to select just the last name (everything before comma), and set it to uppercase.
I may be mixing jQuery and javascript in my example, I'm not positive--still a newb. However, what I've done in the example is to:
function splitLastName(){
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
var lastName = splitNameArray[0];
var firstName = splitNameArray[1];
lastName.wrap('<span class="isUppercase" />');
}​
Basically, I'm setting a variable of the field--I've tested that it accurately grabs the element I want it to grab. I'm turning the string into an array, split by the comma field. Then setting the two parts of the array as their own variables. Finally, attempting to wrap the lastName string in a span that adds the 'isUppercase' class. I know I'm doing something wrong, what is it?
function splitLastName(){
$('[data-dojo-attach-point|="physcianNameNode"]').html(function(i, v) {
var names = v.split(',');
return '<span class="isUppercase">' +names[0] + '</span>,' + names[1];
});
}
Fiddle
.html() docs
The above is a quick solution setting a new innerHTML to the element. If you want to use proper DOM manipulation, it'd be like:
function splitLastName() {
$('[data-dojo-attach-point|="physcianNameNode"]').each(function() {
var names = $(this).text().split(',');
$(this).empty().append($('<span>', {
'class': 'isUppercase',
text: names[0]
}), ',' + names[1]);
});
}
Fiddle
Note that I'm using .each() so the code above will work regardless of $('[data-dojo-attach-point|="physcianNameNode"]') matching multiple elements or just a single one.
The problem is you are trying to split a JQuery object.
I have updated your example: See here
function splitLastName(){
var element = $('[data-dojo-attach-point|="physcianNameNode"]');//find the element
var html = element.html();//get the contents of the DIV element
var splitNameArray = html.split(",");//Split the value with comma
var lastName = splitNameArray[0];//store the last name
var firstName = splitNameArray[1];//store the first name
var newHtml = '<span class="isUppercase">' + lastName + '</span>, ' + firstName;//create the new html using the parsed values
element.html(newHtml);//assign the new html to the original DIV element (overwriting the old)
}
The problem occurs with this line:
var splitNameArray = $('[data-dojo-attach-point|="physcianNameNode"]').split(",");
The notation:
$('< some name >')
is a jQuery selector that selects an element. If you type this into your console (replacing < some name > with your selector) in your browser you'll see that it returns an object not a string. So your code is trying to split an object. I don't know where the string is located (div, span, input box etc.) but you need to pull the string to do the split. If your string is text in a div or span use:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').text()).split(",");
as this will grab the string contained in that selector and then perform the split on it. Likewise, if it is in an input you will need to use the proper handler to get the value:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').val()).split(",");
This will pull the value from an input and then perform the split. If your string is in html then you could alternatively grab it using the following notation:
var splitNameArray = ($('[data-dojo-attach-point|="physcianNameNode"]').html()).split(",");
This will pull the html and perform the respective split operation.
Hope this helps.

jQuery: howto add a <br/> line break in different strings to separate sentences in 2?

I have different sentences which all have double quotes in them, like:
<h3 class="myClass">Sentence one "ends like this"</h3>
<h3 class="myClass">Sentence two"ends like that"</h3>
<h3 class="myClass">Sentence three "another ending"</h3>
All on a page. Basically all values are differents, and I'm trying to have a line break just before the double quote so it would be like
<h3 class="myClass">Sentence one <br/>"ends like this"</h3>
<h3 class="myClass">Sentence two <br/>"ends like that"</h3>
<h3 class="myClass">Sentence three <br/>"another ending"</h3>
I'm kind of confused on which jQuery function should be used to be honest, between split, text ? Any help would be appreciated , I need to understand how to do this... Many thanks!
You can match the <h3> elements, then pass a function to html(). That function will be called for each element, will be passed the current element's inner HTML markup, and must return the new markup.
From there, you can use replace() to insert a <br /> element before the first double quote character:
$("h3.myClass").html(function(index, currentHtml) {
return currentHtml.replace('"', '<br />"');
});
You can test this solution in this fiddle.
Make a function that takes a jQuery object, gets its html, and changes it
function addBR($el) {
Get the element's html
var originalhtml = $el.html();
Split the html by the quotation mark, and join them with a new <br />
var newhtml = originalhtml.split('"').join('<br />"');
Apply the new html
$el.html(newhtml);
And that's it.
Call it with
addBR(jQuery element);
Example: http://jsfiddle.net/XFC5u/
I would take a look at the Javascript split() method but in essence you have the right idea. You want to split based on the double quote(\") and that will return you an array of all the splits where a double quote occurs.
So something like this would happen:
var array = $(".myClass").text().split("\"");
//array = [Sentence one, ends like this, ];
(Not 100% sure if code is right so someone please check ><)
and then from there you can kind of recreate the text with the included . At least that's the process of how I would go about it.
Also just remember that the split method does remove the \" from the array (because it uses it as a limiter to split them) so make sure to readd them when you are recreating the text.
As for if Jquery as a specific way of doing this, I'm not sure. If anyone would like to improve my answer, feel free.
Take a look here to see this code working:
$(".myClass").each(function() {
var text = $(this).text();
var q = text.indexOf('"');
$(this).html(text.substr(0, q) + "<br />" + text.substr(q));
});
just with some basic javascript (inside a jQuery loop offcourse)
​$(".myClass").each(function() { // for each item of myClass
var text = $(this).text(); // temp store the content
var pos = text.indexOf('"'); // find the position of the "
$(this).html(text.slice(0,pos) + '</br>' + text.slice(pos)); // slice before + <br> + slice after = new content
});​​​​​​​​​​
fiddle:
http://jsfiddle.net/JaPdT/
$('.myClass').each(function(){
if($(this).text().indexOf('"') >=0 ){
$(this).text( $(this).text().replace('"', '<br/>"') )
}
})

Categories