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

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/

Related

Replacing/deleting from one character to another JS

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.

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.

Remove BBCode with Regex in Javascript

I am trying to remove BBCode with attributes and content between those tags. I'm using this regular expression that I got here from here. I also tried other regex I found on stackoverflow but they didn't work for me, just the one I copy here is the closest.
([[\/\!]*?[^\[\]]*?])
I added a . before *?]) and it maches the text between the tags but also matches pokemon and I don't want that.
**Regex**: ([[\/\!]*?[^\[\]].*?])
**Text**: I'm a pokemon master and I like
[TAG] this [/TAG] pokemon [TAG] and this [/TAG] text...
I use this web to test regex http://regexpal.com/
Can anyone help me?
Thanks in advance.
str = str.replace(/\[(\w+)[^\]]*](.*?)\[\/\1]/g, '');
jsFiddle.
This is what you want:
.replace(/\[(\w+)[^\]]*](.*?)\[\/\1]/g, '$2');
JavaScript demo
Basically you catch the value between tags and then replace the whole string with that value.
Using a regex to do this isn't a very clean way of doing it though...
Sorry Alex but you didn;t read it seems.
This should do:
\[(\w+).*?\].*?\[/\1\]
This will look for a closing tag matching the opening tag - and also accept attributes on the opening tag. The JavaScript code should then be:
str = str.replace(/\[(\w+).*?\].*?\[\/\1\]/, "");

Use JS to replace text in Gmail message body

I want to write an GnuPG extension for Google Chrome. So far, everything works as expected: If I detect ASCII armored crypt-text, I parse it with my extension and then replace it. (after password has been entered)
Gmail however litters the message body with an insane amount of tags, so my simple JS approach doesn't work anymore. Is there something which can select an certain amount of visible text, no matter how many tags are contained in it, and replace it with some other text? (the tags don't need to survive). ie I want to unencrypt the mailbody in place.
what do you need is something like this:
/<[^>]+>/g
this regexp will remove all tags, an leave plain text...
just gotta replace for nothing... something like this:
"<p>text <b>full</b> of <i>junk</i> and <u>unwanted</u> tags</p>".replace(/<[^>]+>/g, "");
...and about selecting an specific part you can use substring, I guess!
What I really needed to do was a little different:
expand my regex so it didn't care about tags:
var re = /-----[\s\S]+?-----[\s\S]+?-----[\s\S]+?-----/gm;
store all the matches, with tags
use the regex provided by gibatronic to remove tags and then further process the cleaned text using gpg
use body.innerHTML.replace() to replace the matches from 1) with the processed text from 3)
It works now, the only problem is it breaks Gmail. Site layout stays intact, but all buttons and links become defunct. Only solution is to reload the page. Gotta fix this :S

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