I want to get a subset of a string in Javascript. Currently, I only know how to store the entire string:
I have this as a JSON variable with a callback to foo:
foo({"results":[
"<div id=\"following\"><span>Obama</span></div>"
]})
And this is my callback function:
function foo(o){
var entireDiv = o.results[0];
}
How do I store just the "< a href = ... > ... < / a>
" tag as a string in Javascript?
With jQuery, you can parse in a piece of HTML as the second argument.
So, to update your foo function:
$j = jQuery.noConflict();
function foo(o)
{
var JustTheLink = $j( 'a' , o.results[0] ).parent().html();
}
Update:
With multiple links to handle, you can do this:
function foo(o)
{
$j('a',o.results[0]).each(handleSrc);
}
function handleSrc()
{
console.log(this); // tag
console.log($j(this).html()); // contents
}
You can use a regular expression to find the anchor tag:
function foo(o){
var entireDiv = o.results[0];
var link = /<a.+?\/a>/.exec(entireDiv)[0];
}
var link = entireDiv.match(/<a[^>]*>.*<\/a>/);
Related
So I want to get the Object which is essentialy a string. The issue is I cant transfer it into the string format since the resulting string is just anything but the thing I want. Bringing the object into a json doesnt bring a proper string either so my only way of achieving that is the concat method.
I have a Popup-Love which returns the string as follows foo, foo1 ,foo2 while I need it as
'foo1','foo2',...,'foo999' .
My method manages to do that for the first element while all the other elements remove the apostrophe resulting in something like 'foo,foo1,foo2'. How do i fix that?
var i = 0;
if(i == 0){
var t ="'";
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
i = i +1;
} else {
var t = t.concat("'");
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
}
You can "overwrite" the native toString() function of the Object and replace it with a function that does what you want. Something like below
function MyObj(){
this.creationTime = new Date().toLocaleString();
}
MyObj.prototype.toString = function something(){
return 'I was created on ' + this.creationTime;
}
var myObj = new MyObj();
console.log('String version of my custom object: ' + myObj);
I am calling a function getParentElm(idStr,element) which accepts an id and an element, and searches up the html tree until it finds a parent element which has an id equal to idStr.
Calling code:
var s = "someId";
var el = getParentElm(s,element);
I would like the idStr parameter to work with strings that match to "someId", for eg "someId123".
I tried :
var s = "/someId/";
but it did not work. Ideally, i do not want to touch the getParentElm function.
Update: Thanks vbranden.
I tried: var s = /someId/ and that worked. I upvoted your comment. Thanks all :)
no regex needed.
use closest to traverse up the dom, and id* to match id's which contains your idStr.
function getParentElm(idStr,element){
return $(element).closest('[id*="' + idStr + '"]');
}
Here, this should work :
function getParentElm(idStr,element) {
var patt = new RegExp(idStr +".*");
while(element.parentNode)
{
if(patt.test(element.parentNode.id))
return element.parentNode;
element=element.parentNode;
}
return false;
}
And just call the function in this way :
var el = getParentElm("someId",document.getElementById('foo'));
I want to replace string & amp;LF; with < br>< /br> tags.
in paragraph:
<p id="adres" class="p1">aaaaa&LF;aaaaa&bbbbb&LF;bbbbb&LF;< /p>
using funtion:
var str = document.getElementById("adres").innerHTML;
var res = str.replace("&LF;", "<br/>");
document.getElementById("adres").innerHTML = res;
I call this function in body tag as:
<body onload="myFunction();">
But it replaces only first row.
How can I replace all rows in html document I got?
id is for a single element. So it should change the value for that particular element.
if you want to use id try something like;
id='adres1'
id='adres2'
id='adres3'
and in function
var str,n, xy;
for(n=1; n<4; n++)
{
xy = "adres"+n;
str = document.getElementById(xy).innerHTML;
var res = str.replace("&LF;", "<br/>");
document.getElementById("adres").innerHTML = res;
}
this is to get you started, you can make the code neater than this.
first update your replace code by
var res = str.replace(/&LF;/g, "<br/>");
since you all the paragraphs are containing the same class name then you can simply fetch all the element in one variable and iterate through it.
please refer below fiddle example to see working code
http://jsfiddle.net/py3dzzrv/
Try changing the replace function to the following, which includes the global replacement option /g. It should work.
var res = str.replace( /&LF;/g,"< br/>");
Here is the function
function addCategory(category) {
$('#category_choice').append($('#!the variable "category" has to go in here!'));
$('#feed_submit_categories').hide();
}
The "category" variable sends the id of the element that has to be appended. How can I insert the "category" var into the function? In PHP it is much easier having $var_name tags... But here, I have no idea as to how to include it.
function addCategory(category) {
$('#category_choice').append($('#'+category));
$('#feed_submit_categories').hide();
}
Simple example of concatenation ( variables, string ):
var h = "Hello";
var w = "World!";
alert( h+w ); // HelloWorld!
alert( h+' '+w); // Hello World!
alert( h+' my dear '+w); // Hello my dear World!
jQuery selector can use string to represent literally an element ID selector:
$('#element')
that means you keep as string what you need and you concatenate a variable to it:
var elName = "element"; // string variable
$('#'+ elName) // same as: $('#element')
If you need to append every time a new fresh element do like:
$('#category_choice').append('<div id="'+category+'" />');
just make sure not to duplicate your elements ID for ID has to be unique per page element.
Use
function addCategory(category) {
$('#category_choice').append( $('#'+category) );
$('#feed_submit_categories').hide();
}
$('#category_choice').append($('#'+category));
jQuery selectors are just strings that are evaluated, you can generate a string following basic Javascript rules.
For example :
var iAmString = "#"+category;
$(iAmString) //<-- using string var as a selector
I'm trying to extract a URL from an array using JS but my code doesn't seem to be returning anything.
Would appreciate any help!
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
function url1_m1(pages, pattern) {
var URL = '' // variable ready to accept URL
for (var i = 0; i < pages[i].length; i++) {
// for each character in the chosen page
if (pages[i].substr(i, 4) == "www.") {
// check to see if a URL is there
while (pages[i].substr(i, 1) != "|") {
// if so then lets assemble the URL up to the colon
URL = URL + pages[i].substr(i, 1);
i++;
}
}
}
return (URL);
// let the user know the result
}
alert(url1_m1(pages, "twitter")); // should return www.twitter.com
In your case you can use this:
var page = "www.facebook.com|Facebook";
alert(page.match(/^[^|]+/)[0]);
You can see this here
It's just example of usage RegExp above. Full your code is:
var pages = [
"www.facebook.com|Facebook",
"www.twitter.com|Twitter",
"www.google.co.uk|Google"
];
var parseUrl = function(url){
return url.match(/^(www\.[^|]+)+/)[0];
};
var getUrl = function(param){
param = param.toLowerCase();
var page = _(pages).detect(function(page){
return page.toLowerCase().search(param)+1 !== 0;
});
return parseUrl(page);
};
alert(getUrl('twitter'));
You can test it here
In my code I have used Underscore library. You can replace it by standard for or while loops for find some array item.
And of course improve my code by some validations - for example, for undefined value, or if values in array are incorrect or something else.
Good luck!
Im not sure exactly what you are trying to do, but you could use split() function
var pair = pages[i].split("|");
var url = pair[0], title=pair[1];