Replacing/deleting from one character to another JS - javascript

I'm currently writing a program that needs to delete/replace with "" from one character to another, heres an example:
<p id="p1">Hey! I'm a good stringexcept im here! I wish that <a> tag was gone! </p>
How would I use JavaScript to delete everything from <a to </a>? I have a bunch of way I could solve this, but they are uselessly complicated. Any advice on an easy way to do this?
BONUS POINTS: Any idea what to do for when I would want the <a> tags gone, but the text inside it ("except im here") to remain? Same issue. I could solve it, but it would be overly complicated.

An easy way to do this would be to use regex, if you already have the text;
string.replace(/<[^>]*>?/gm, '');
So in your case, lets say you get the string with innerHTML;
var p1 = document.getElementById("p1").innerHTML;
var yourDesiredFormat = p1.replace(/<[^>]*>?/gm, '');
As comment from #Saiansh Singh suggests, you can also use the native textContent property of a DOM object;
var p1 = document.getElementById("p1").textContent;
Both of these would give you;
Hey! I'm a good stringexcept im here! I wish that tag was gone!
For your input.

Related

How to Grab Selected str.replace Value From Regex in JS

Ok, I understand how the title might be a bit confusing, let me elaborate.
So to start I am making a BBCode input section. Then it will transfer the code from BBCode to HTML. Now the problem is I am having MINIMAL issues. Let me post my code before I continue:
var newer = $('#my_textarea').val().replace(/\[b\]/gi, '<b>');
Now let me say this, it replaces the [b] tags correctly with the <b> tags. My problem is I do not know how to do that for all tags. I have tried shortening the code by using this:
var newer = $('#my_textarea').val().replace(/\[(?:b|u|i)\]/gi, '<???>');
Then it will replace all tags (bold, underline, and italicize) with the correct HTML tags. Yet how would I go about doings this? How would I replace the HTML tag with the the BBCode tag found? What I mean is with this part of the regex (?:b|u|i) where it selects any of the three letters, how could I add that same letter to the HTML tag? Do you understand what my problem is? :) Please Help, Thank You!!
Use the $2 to get the second selected group
var newer = $('#my_textarea').val().replace(/(\[(b|u|i)\])/gi, '<$2>');
A good site for understanding and creating RegEx: https://regex101.com/
To catch also [b],[u],[i] and also [\b],[\u],[\i] use the following:
var newer = $('#my_textarea').val().replace(/(\[((\/?)(b|u|i))\])/gi, '<$2>');
The regex below will convert the BBCode to HTML:
result = subject.replace(/\[(b|i|p)\](.*?)\[\/(b|i|p)\]/g, "<$1>$2</$3>");
You'll need to add more tags but you get the idea.
Demo
http://jsfiddle.net/tuga/sp5597aj/1/

Using the `content` attribute as an HTML Template

I've been trying to use the CSS content property to make somewhat of a "template" for an element of a specific class.
I've tried multiple things. . .
Many places I have seen told me to convert everything to hexadecimal, so I did, until I saw that using hex wrote the litteral characters into the element, instead of evaluating the characters as HTML.
I then tried just litterally entering the characters into the content, and I got the exact same result (this makes it appear as if there is no purpose for the hex, yet thats hard to belive with how many people say there is. . . ).
Is there any way that I can place HTML content into an element using the CSS content attribute?
I've made a JS-Fiddle for this:
And, of course, Stack wants my source:
HTML:
<button id="normal" >Show with normal output</button>
<button id="hex" >Show with Hexadecimal output</button>
<div id="class_changer" ></div>
JS:
function changeClass(evt)
{
class_changer.className = evt.srcElement.id;
}
var class_changer = document.getElementById('class_changer');
var normal = document.getElementById('normal').addEventListener('click', changeClass, true);
var hex = document.getElementById('hex').addEventListener('click', changeClass, true);
And the un-godly long CSS:
.normal::before {
content: '<img alt="Facebook" src="http://cache.addthis.com/icons/v1/thumbs/32x32/facebook.png" />';
}
.hex::before {
content: '\0027\003c\0061\0020\0068\0072\0065\0066\003D\0022\0068\0074\0074\0070\003A\002F\002F\0061\0070\0069\002E\0061\0064\0064\0074\0068\0069\0073\002E\0063\006F\006D\002F\006F\0065\0078\0063\0068\0061\006E\0067\0065\002F\0030\002E\0038\002F\0066\006F\0072\0077\0061\0072\0064\002F\0066\0061\0063\0065\0062\006F\006F\006B\002F\006F\0066\0066\0065\0072\003F\0070\0063\006F\003D\0074\0062\0078\0033\0032\006E\006A\002D\0031\002E\0030\0026\0061\006D\0070\003B\0075\0072\006C\003D\0068\0074\0074\0070\0025\0033\0041\0025\0032\0046\0025\0032\0046\0077\0077\0077\002E\0063\0069\006D\0074\0072\0061\006B\002E\0063\006F\006D\0026\0061\006D\0070\003B\0075\0073\0065\0072\006E\0061\006D\0065\003D\0063\0069\006D\0063\006F\0072\0022\0020\0074\0061\0072\0067\0065\0074\003D\0022\005F\0062\006C\0061\006E\006B\0022\003e\003c\0069\006D\0067\0020\0061\006C\0074\003D\0022\0046\0061\0063\0065\0062\006F\006F\006B\0022\0020\0073\0072\0063\003D\0022\0068\0074\0074\0070\003A\002F\002F\0063\0061\0063\0068\0065\002E\0061\0064\0064\0074\0068\0069\0073\002E\0063\006F\006D\002F\0069\0063\006F\006E\0073\002F\0076\0031\002F\0074\0068\0075\006D\0062\0073\002F\0033\0032\0078\0033\0032\002F\0066\0061\0063\0065\0062\006F\006F\006B\002E\0070\006E\0067\0022\0020\002F\003e\003c\002F\0061\003e';
}
Check it out at JS-Fiddle and see what you can do! Let me know! Thanks everybody!
UPDATE: SOLVED (ish...)
Yes, wierd question sometimes accept wierd answers (like iterating over the DOM...) but if you have a better solution, I'm all ears.
As it turns out, the accepted answers means of evaluating a "CSS template" may be the best means of performing "templating" without the use of third-party libraries or the new <template> tag (that I'm still not sure of) even though it makes my skin crawl (if anyone has a better solution, please post it). Either way, I've updated my JSFiddle, so check it out!
Although, I guess the best answer would be purely making a template as a string in JavaScript, that is, if we are going to be evaluating it later on and pre-pending it to an element. Yea, that would make more sense...
No, this is not possible with plain CSS. However, if you really want to save these templates in CSS, you could iterate over all elements and use
window.getComputedStyle(element, ':before').content
to fetch the content and then prepend/append it to the element. To parse the HTML, you could either use jQuery.parseHTML, new DOMParser().parseFromString or a dummy DOM element. Alternatively, you could also use .innerHTML directly, but I wouldn't recommend that..

Javascript: get plain text inside a span which has other nested tags present

Just for you guys to note, of course I have read this first:
Javascript get text inside a <span> element
However, my case is not that easy, let alone because I need to do it natively, without jQuery.
Supposing we have this on an arbitrary web page:
<span id="entry1" class="entries">
<img src="http://whereyourpicis.at/pic.jpg" border="0">
++ This is the plain text we want to get from the SPAN block. ++
<span id="nested2"><a onclick="doSomething()">Action!</a></span>
</span>
I've tried anything imaginable, but I can't say any of the "solutions" I tried was a good one, since it feels like a total kludge taking the whole innerHTML and then doing some sed-style regex magic on it.
There must be a more elegant way to accomplish this, which is why I'm asking here.
BTW I've also found out that even nextSibling() cannot work here.
I am not sure this is what you need, because you didn't specify what you need to be an exact output in your example code.
If you need to literally Strip HTML from Text JavaScript
you could use function like this:
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
please check this: http://jsfiddle.net/shershen08/7fFWn/3/
If you want to get only the text nodes within an element, I think you'll need to iterate over the element's childNodes and fetch the text nodes. Here's a quick-and-dirty example of a function that will fetch only the text nodes from a given element (it also skips any text nodes that are just whitespace, since those are often added as a result of HTML formatting but don't really mean anything to a human).

How to replace tags with a javascript function from beginning to end?

Here is my problem, while using the replace javascript function in order to replace html tags with BBcode tags, I encountered this issue:
What I wanted:
[b]Some text[/b], with some [b]other text[/b].
What I've got:
[b]Some text</b>, with some <b>other text[/b].
This is basically the way I wrote this:
mystring.replace(new RegExp('<b>(.*)</b>','gi'),'[b]$1[/b]');
I know that with that example I could simply replace it this way:
mystring.replace('<b>','[b]').replace('</b>','[/b]');
But the thing is that I want to use it with some divs with a specific ID... If I were to do this by replacing opening and ending tags separately, then I wouldn't be able to replace the '</div>' properly.
Is there a way to have this function run through the string "linearly", from beginning to end, rather than from the extremities towards the center ? (My biggest problem is really that I am not able to formulate this question properly, hence the lack of results while searching the web.)
Thank you for any input you may provide.

Regex replace string but not inside html tag

I want to replace a string in HTML page using JavaScript but ignore it, if it is in an HTML tag, for example:
visit google search engine
you can search on google tatatata...
I want to replace google by <b>google</b>, but not here:
visit google search engine
you can search on <b>google</b> tatatata...
I tried with this one:
regex = new RegExp(">([^<]*)?(google)([^>]*)?<", 'i');
el.innerHTML = el.innerHTML.replace(regex,'>$1<b>$2</b>$3<');
but the problem: I got <b>google</b> inside the <a> tag:
visit <b>google</b> search engine
you can search on <b>google</b> tatatata...
How can fix this?
You'd be better using an html parser for this, rather than regex. I'm not sure it can be done 100% reliably.
You may or may not be able to do with with a regexp. It depends on how precisely you can define the conditions. Saying you want the string replaced except if it's in an HTML tag is not narrow enough, since everything on the page is presumably within some HTML tag (BODY if nothing else).
It would probably work better to traverse the DOM tree for this instead of trying to use a regexp on the HTML.
Parsing HTML with a regular expression is not going to be easy for anything other than trivial cases, since HTML isn't regular.
For more details see this Stackoverflow question (and answers).
I think you're all missing the question here...
When he says inside the tag, he means inside the opening tag, as in the <a href="google.com"> tag...This is something quite different than text, say, inside a <p> </p> tag pair or <body> </body>. While I don't have the answer yet, I'm struggling with this same problem and I know it has to be solvable using regex. Once I figure it out, i'll come back and post.
WORKAROUND
If You can't use a html parser or are quite confident about Your html structure try this:
do the "bad" changing
repeat replace (<[^>]*)(<[^>]+>) to $1 a few times (as much as You need)
It's a simple workaround, but works for me.
Cons?
Well... You have to do the replace twice for the case ... ...> as it removes only first unwanted tag from every tag on the page
[edit:]
SOLUTION
Why not use jQuery, put the html code into the page and do something like this:
$(containerOrSth).find('a').each(function(){
if($(this).children().length==0){
$(this).text($(this).text().replace('google','evil'));
}else{
//here You have to care about children tags, but You have to know where to expect them - before or after text. comment for more help
}
});
I'm using
regex = new RegExp("(?=[^>]*<)google", 'i');
you can't really do that, your "google" is always in some tag, either replace all or none
Well, since everything is part of a tag, your request makes no real sense. If it's just the <a /> tag, you might just check for that part. Mainly by making sure you don't have a tailing </a> tag before a fresh <a>
You can do that using REGEX, but filtering blocks like STYLE, SCRIPT and CDATA will need more work, and not implemented in the following solution.
Most of the answers state that 'your data is always in some tags' but they are missing the point, the data is always 'between' some tags, and you want to filter where it is 'in' a tag.
Note that tag characters in inline scripts will likely break this, so if they exist, they should be processed seperately with this method. Take a look at here :
complex html string.replace function
I can give you a hacky solution…
Pick a non printable character that’s not in your string…. Dup your buffer… now overwrite the tags in your dup buffer using the non printable character… perform regex to find position and length of match on dup buffer … Now you know where to perform replace in original buffer

Categories

Resources