JQuery : Delete span from title tag - javascript

Please how can I get a span into title tag i try to use
console.log($('title > span').text());
but it return an empty result. For example I want to get the word beautiful from this code :
<title>lorem epsum dolor <span class="spa">beautiful</span></title>

<title> tag should not include any-other tags inside it.
as stated here https://www.w3.org/TR/html401/struct/global.html#h-7.4.2
Titles may contain character entities (for accented characters, special characters, etc.), but may not contain other markup (including comments).

try this:
$('title span').html()

As Nate mentioned, a span tag is not valid within a title tag. However, if you still need to process it for whatever reason (for instance, a dynamically generated title from a database), you could use a regular expression.
<script>
var titleTag = $('title').text();
var match = titleTag.match(/<span>(.+)<\/span>/);
console.log(match[1]);
</script>

Related

RegEx to only look at text inside HTML tags?

I recently started learning/using about RegEx.
Is there a way to avoid matching words that are HTML tag attributes or belonging to tag attributes?
For example:
<p style=“position: absolute”>position: </p>
I tried
/\bposition\b\W\s/g
But that matches both instances.
Can I only match the second “position: “?
Clarification:
I am trying to search the document for words that the user enters and replace them with a span element containing those words - this is similar to "Ctrl + F". Simply having the text is not enough as I would need a way to also update the document once the text was replaced with the span elements.
Disclaimer: Use stuff like document.innerText and other DOM APIs rather than Regex.
Match HTML tags:
<.+?>/g
Match everything within HTML tags (should handle nested ones as well):
/(?<=<.+.>)(.*?)(?=<.*\/.+.?>)/g
https://regex101.com/r/2uZHli/ for example of the above.
The RegEx to match the HTML / XML tags is /(<([^>]+)>)/ig. Maybe be this is what you're looking for.
let str = '<p style="position: absolute">position: </p>';
const strWithoutTag = str.replace(/(<([^>]+)>)/ig, '');
console.log(strWithoutTag);
You can try the Regex to match your temp, which matched the second "position: ".
/(?=\b.*(?<yourKeyword>position).*\b)(?<=<[^]*>)([^<>]+)(?=<\/([^<>]*)>)/g

How to render only parts of a string as HTML

I want to render a text as common HTML and parse occurrences of [code] tags that should be output unrendered - with the tags left untouched.
So input like this gets processed accordingly:
<p>render as HTML here</p>
[code]<p>keep tags visible here</p>[/code]
<p>more unescaped text</p>
I've regexed all code-tags but I have no idea how to properly set the text of the element afterwards. If I use jQuery's text() method nothing gets escaped, if I set it with the html() method everything gets rendered and I gained nothing. Can anybody give me a hint here?
Try replacing [code] with <xmp> and [/code] with </xmp> using regex or alike, and then use the jQuery html() function.
Note that <xmp> is technically deprecated in HTML5, but it still seems to work in most browsers. For more information see How to display raw html code in PRE or something like it but without escaping it.
You could replace the [code] and [/code] tags by <pre> and </pre> tags respectively, and then replace the < within the <pre> tags by & lt;
A programmatic solution based on Javascript is as follows
function myfunction(){
//the string 's' probably would be passed as a parameter
var s = "<p>render as HTML here</p>\
[code]<p>keep tags visible here</p>[/code]\
<p>more unescaped text</p>";
//keep everything before [code] as it is
var pre = s.substring(0, s.indexOf('[code]'));
//replace < within code-tags by <
pre += s.substring(s.indexOf('[code]'), s.indexOf('[/code]'))
.replace(new RegExp('<', 'g'),'<');
//concatenate the remaining text
pre += s.substring(s.indexOf('[/code]'), s.length);
pre = pre.replace('[code]', '<pre>');
pre = pre.replace('[/code]', '</pre>');
//pre can be set as some element's innerHTML
return pre;
}
I would NOT recommend the accepted answer by Andreas at all, because the <xmp> tag has been deprecated and browser support is totally unreliable.
It's much better to replace the [code] and [/code] tags by <pre> and </pre> tags respectively, as raghav710 suggested.
He's also right about replacing the < character with <, but that's actually not the only character you should replace. In fact, you should replace character that's a special character in HTML with corresponding HTML entities.
Here's how you replace a character with its corresponding HTML entity :
var chr = ['&#', chr.charCodeAt(), ';'].join('');
You can replace the [code]...[/code] with a placeholder element. And then $.parseHTML() the string with the placeholders. Then you can insert the code into the placeholder using .text(). The entire thing can then be inserted to the document (run below or in JSFiddle).
var str = "<div><b>parsed</b>[code]<b>not parsed</b>[/code]</div>";
var placeholder = "<div id='code-placeholder-1' style='background-color: gray'></div>";
var codepat = /\[code\](.*)\[\/code\]/;
var code = codepat.exec(str)[1];
var s = str.replace(codepat, placeholder);
s = $.parseHTML(s);
$(s).find("#code-placeholder-1").text(code);
$("#blah").html(s);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Text
<div id="blah">place holder</div>
Around
The code above will need some modifications if you have multiple [code] blocks, you will need to generate a unique placeholder id for each code block.
If you may be inserting untrusted structure code, would highly recommend using large random number for the placeholder id to prevent a malicious user from hijacking the placeholder id.

js regex: replace a word not follows or not followed by a certain word

I want to replace the "word" that is outside "span", and keep the other that is inside "span". By now, the following code works when both are following "mark>" and followed by "span". But I want to go further, following "mark>" OR being followed by "span", any one of the two condition should cause replacing action.
var replaceString = "newWord";
var htmlString = "This <span style='color:red' title='mark'>normal word</span> need no change. This word is to be replaced. <span>Another word</span> need no change.";
var reg=new RegExp("(?!mark>)"+replaceString+"(?!<\/span>)","gi");
var bb=htmlString.replace(reg,replaceString);
alert(bb)
// Final result should be "This <span style='color:red' title='mark'>normal word</span> need no change. This newWord is to be replaced. <span>Another word</span> need no change.";
UPDATE: using title as mark. adding starting tag span
UPDATE: Follow the suggestion below, I'm trying to solve the problem in anohter way, see here: js regex: replace words not in a span tag
Would you be comfortable using another span tag ?
By putting a class name inside it, you should be able to change the words you need to change by changing the content of every span containing that class.
Something like :
This <span style='color:red' mark>word</span> need no change. This <span class='changeMe'>word</span> is to be replaced. Another word</span> need no change.
And a jQuery script going
$('.changeMe').text("newWord")
If you still want to use Regexp, for an OR condition, you might just do it twice :
var reg=new RegExp("(?!mark>)"+replaceString,"gi");
var bb=htmlString.replace(reg,replaceString);
reg=new RegExp(replaceString+"(?!<\/span>)","gi");
bb=htmlString.replace(reg,replaceString);
You are looking for negative look-aheads (or Lookbehinds) which JS, unfortunately, doesn't support. Check http://www.regular-expressions.info/javascript.html
You may try the following Regex:
var reg = new RegExp('[^(mark>)]word[^(</span>)]', "gi")
htmlString.replace(reg, " newWord "); //Check the spaces
I would rather suggest using JS to get DOM elements and replace text iterative-lly (not sure if it's a word, even a jargon).
HTH

Javascript regular expression prevent matching inside tags

I have to match a string that is not inside tags. I am working on projects that I don't have control over the back-end html rendering code. What I need to do is add a hover functionality for multiple dynamic words. I created a script that will look for those key words in specific elements and add their description in title tags for the hover. My problem is that if other keywords are found in other keyword's title tags.
My JS:
var str = 'match <span title="not match here">match</span> match';
str.replace( /match/gim, 'ok' );
I do not want the "match" word in the title attribute to be replaced, my desired result is:
'ok <span title="not match here">ok</span> ok'
how can I do that with Javascript?
I tried the expression below but it's not working for me:
^((?!(".+")match)*$
You need to capture tags first to be able to avoid them:
var result = str.replace(/(<[^>]*>)|match/gi, function (_,g1) {
return (g1==undefined)? 'ok':g1;
});
But if you can, using the DOM is probably the best way.

Why JavaScript converts my < into >

JavaScript converts my < into >. I want to alert it but my message is with encoded marks like ##&*()}{>?>? - how to display it normally but prevent from executing as HTML code?
<span id="ID" onClick="alertIt(this.id);">
<p>Some string with special chars: ~!##&*()}{>?>?>|{">##$#^#$</p>
<p>Why when clicked it gives something like this:</p>
<p>'<br>
Some string with special chars: ~!##&*()}{>?>?>|... and so on
<br>'</p>
</span>
<script type="text/javascript">
function alertIt(ID)
{
var ID = ID;
var content = document.getElementById(ID).innerHTML;
alert(content);
}
</script>
Use innerText instead of innerHTML. http://jsfiddle.net/WVf95/
Your problem is that you use the wrong approach to get the text to display with alert().
Some characters are illegal in HTML text (they are used for HTML tags and entities). innerHTML will make sure that text is properly escaped (i.e. you can see tags and escaped text).
If you want to see tag and text in alert(), there is no solution.
If you want only the text, then you will have to extract it yourself. There is no built-in support for that. It's also not really trivial to implement. I suggest to include jQuery in your page; then you can get the text with:
function alertIt(ID) {
alert($(ID).text());
}
Using textContent instaed of innerHTML or innerText is a solution.

Categories

Resources