Javascript: string regex - javascript

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

Related

HTML DOM check if the text of an element includes specific text?

How to check if an element's innerHTML includes "as me to" (the whole phrase and not just if it includes one of the words)?
I know that it is pretty short, but the question is already stated in the title.
you can use indexOf()
var str = $('some selector id').innerHTML();
var result = str.indexOf("as");
if result is -1 then there is no instance of "as" in the given string.
You can check it using RegExp. If the element has given string, the test() function will return true or false if it's not.
function check(elem, str) {
var element = document.getElementById(elem).innerHTML,
rg = new RegExp(str, 'g'),
res = rg.test(element);
console.log(`Does the ${elem} element contains ${str} - ${res}`);
return res;
}
check('p', 'as');
check('p', 'something');
<p id='p'>ashamed</p>
Try this!
HTML
<div id="source">this word as </div>
JAVASCRIPT
var sourceEl = document.getElementById('source');
if (sourceEl.textContent.includes('as'))
{
alert("Exist");
}
https://jsfiddle.net/n3zkzy1g/5/

javascript find element with string as id

I'm trying to write a function to with the element in my page with id equal to a string, and append children to that element. However I'm not so familiar with JS and don't know what's wrong with my function. Here is the function. The "set" is just an array as string set(It contains multiple names).
function printNetwork(set,id){
console.log("id is "+id);
var node=document.getElementById(id);
console.log("found"+node);
for(var s in set){
var className="leaf";
var content = document.createTextNode("<p class="+className+">"+s+"</p>");
console.log(content);
node.appendChild(content);
}
}
And then I called the function:
var ced ="${commented}";
console.log(ced);//ced is like "["Mike"]"
var cedArr = JSON.parse(ced.replace(/"/g, '"'));//parse it back to set
console.log(cedArr);
printNetwork(cedArr,"ced");
Reading the log from console it says "node" is foundnull, and "content" is "<p class=leaf>0</p>" and appendChild failed.
My question is, how can I pass the id into the function where it searches element by the argument? I'm used to the way Java works and now I'm a little confused with how JS works...
Suggestions are appreciated!!
Seems to work, i've used a different array than yours to make the example simple, but my guess is that you don't have any element with id ced in your DOM:
function printNetwork(set,id){
console.log("id is "+id);
var node=document.getElementById(id);
console.log("found"+node);
for(var s in set){
var className="leaf";
var content = document.createTextNode("<p class="+className+">"+s+"</p>");
console.log(content);
node.appendChild(content);
}
}
var ced = {"a": "a", "b": "b"};
printNetwork(ced,"ced");
And html:
<div id="ced"></div>
http://jsfiddle.net/eakvdr7L/

how to use function to all row in html document

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

Replace n patterns in a string

Is there an easy way to fix this code:
title_1 = $(this).closest('tr').find('td').html();
title_2 = $(this).closest('tr').find('td').next().html();
title_3 = $(this).closest('tr').find('td').next().next().html();
question = question.replace(/{title_1}/g, title_1);
question = question.replace(/{title_2}/g, title_2);
question = question.replace(/{title_3}/g, title_3);
So it isn't so dully (repeated) and can cover n occurences of title_ pattern?
I'm a beginner Javascript developer and a complete regular expressions newbie (actually, they scare me! :|), so I'm unable to do this by myself. I've tried to look for an inspiration in different languages, but failed.
You can use a function in the replace, to get the value depending on what you find:
question = question.replace(/{title_(\d+)}/g, $.proxy(function(x, m){
return $(this).closest('tr').find('td:eq('+(m-1)+')').html();
}, this));
Demo: http://jsfiddle.net/n3qrL/
String.prototype.replace() could take a function as second parameter.
var $this = $(this);
question = question.replace(/\{title_(\d+)\}/g, function(match, n) {
return $this.closest('tr').find('td').eq(n - 1).html();
});
Demo Here
Try this ,
Generalized for getting all td tag's text value :
$("table").find("tr").each(function(){
$(this).find("td").each(function(){
alert($(this).html());
var txt=$(this).html();
//var pattern="/{"+txt+"}/g";
//question = question.replace(pattern, txt);
});
});
NB. In your question you have not mentioned the value for 'question' . please define value for 'question'
It seems to me that you want to get the text content of the first three cells of a table row and use it to replace the content of a string, and that this is an element somewhere in the row. So you can do:
var n = 3; // number of cells to get the text of
var textArray = [];
var tr = $(this).closest('tr')[0];
var reString;
for (var i=0; i<n; i++) {
reString = '{title_' + (i+1) + '}';
question = question.replace(reString, tr.cells[i].textContent);
}
If you wish to avoid jQuery's closest, you can use a simple function like:
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
do {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
} while (el.parentNode)
}
then:
var tr = upTo(this, 'tr');

How to get title tag in a string of html?

Hey i'm loading an html page using ajax into a string, now i want to find the title of the page and use it.
Now i did manage to get the <title> using regex but that returns the tag along with the title itself and i wish to extract that from the string or could there be a way to do that in the regex?
This is my code :
var title = result.match(/<title[^>]*>([^<]+)<\/title>/);
Now how do i get the actuall title after this/ instead of this?
.match() returns array of matches, use
var title = result.match(/<title[^>]*>([^<]+)<\/title>/)[1];
to get value in parentheses
load your response html string into a jQuery object like so and retrieve the text
$(response).find("title").text();
A relatively simple plain-JavaScript, and non-regex, approach:
var htmlString = '<head><title>Some title</title></head><body><p>Some text, in a paragraph!</p></body>',
html = document.createElement('html'),
frag = document.createDocumentFragment();
html.innerHTML = htmlString;
frag.appendChild(html);
var titleText = frag.firstChild.getElementsByTagName('title')[0].textContent || frag.firstChild.getElementsByTagName('title')[0].innerText;
console.log(titleText);​
JS Fiddle demo.
I've, obviously, had to guess at your HTML string and removed the (presumed-present) enclosing <html>/</html> tags from around the content. However, even if those tags are in the string it still works: JS Fiddle demo.
And a slightly more functional approach:
function textFromHTMLString(html, target) {
if (!html || !target) {
return false;
}
else {
var fragment = document.createDocumentFragment(),
container = document.createElement('div');
container.innerHTML = html;
fragment.appendChild(container);
var targets = fragment.firstChild.getElementsByTagName(target),
result = [];
for (var i = 0, len = targets.length; i<len; i++) {
result.push(targets[i].textContent || targets[i].innerText);
}
return result;
}
}
var htmlString = '<html><head><title>Some title</title></head><body><p>Some text, in a paragraph!</p></body></html>';
var titleText = textFromHTMLString(htmlString, 'title');
console.log(titleText);​
JS Fiddle demo.
CODE:
var title = result.match("<title>(.*?)</title>")[1];
Make the reg exp to case insensitive.
Here is the complete code:
var regex = /<title>(.*?)<\/title>/gi;
var input = "<html><head><title>Hello World</title></head>...</html>";
if(regex.test(input)) {
var matches = input.match(regex);
for(var match in matches) {
alert(matches[match]);
}
} else {
alert("No matches found!");
}
try this I think this will help. It perfectly works in my case. :)
var FindTag=(data='',tag='')=>{
var div=document.createElement('div');
div.innerHTML=data;
data=$(div).find(tag)[0].outerHTML;
return data;
}
var data=FindTag(data,"title");
Regular expressions aren't a good way to look for things in HTML, which is too complex for a simple one-off regex. (See the famous post on this topic.) Instead, use DOMParser's parseFromString and then look in the resulting document:
const html = "<!doctype html><head><title>example</title>";
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
const title = doc.querySelector("title");
console.log(title.textContent);

Categories