I'm having difficulties in executing what I want to achieve, it may just be sleep deprivation but it's more likely that regex is not my strong suit, I just can't quite get my head around it, but hopefully someone can give me a hand here.
I have the following string:
<span class="comment"><!--Some string\nsome other string\nsome more string--></span>
I need to format it so that it looks like this:
<span class="comment"><!--Some string</span>\n<span class="comment">some other string</span>\n<span class="comment">some more string--></span>
Now this would be really easy if this was the only string as I could do something like this:
/</span>\n<span class="comment">/gi
However the formatting should only happen if the corresponding open </span> has the class "comment" the other issue is that the open span tag with the class comment is not necessarily the first word of the string, there could be a string in-front of it and there could be infinitely many \n within the span...e.g. another variation could look like this:
<<span class="tag">string1\nstring2</span>><span class="comment"><!--string\nanother random string--></span>
No formatting should take place within the span with class tag, however formatting should take place in the span with class comment.
This is rather challenging for me to get my head around, the closest I have gotten is the following:
regex:
/<span class="comment">([^\<\/]*)\n/gi
replacement:
<span class="comment">$1</span>\n<span class="comment">
This gets close, as it formats the last line and first line within the span with class comment, but not the lines in between.
There may be javascript solutions to do this, but if at all possible I would prefer using regex.
Here you go,
str.replace (/<span\s+class="comment">.*<\/span>/ig, function (m) {
return m.replace (/\n/g, '</span>\n<span class="comment">');
});
Extract the span and its contents, then replace all the \n in that part.
Related
Given this text:
<span class='green'>foobar</span> something <span class='red'>fizzle</span>
I need to somehow attain this:
<tagA>foobar</tagA> something <tabB>fizzle</tagB>
I basically have to match <span class='green'>*anything*</span> and be able to differentiate it from the red one as well. I have to take this green span on both ends and replace it with a fixed string, but somehow retain whatever text is between the two tags.
I swear I've looked around a ton but have no idea how to find the solution for this with regex.
This should do the trick
Replace
<span class='green'>(.*?)</span>
With
<tagA>$1</tagA>
And do something similar for the class with the value red
Update 1
Response to feedback "What if something contains a newline?"
If I remember correctly JavaScript does not support the "single line mode" / Dot matches line breaks.
<span class='green'>([\s\S]*?)</span>
Update 2
This tweaked regex allows
<span\s+class\s*=\s*['"]green['"]\s*>([^>]*)</\s*span\s*>
white space where the html spec is allowing it
accepts single as well as double quotes for the attribute values
matches the value between the tags using a negated character class which is qualified greedy resulting in better performance generally and is also supported by JavaScript
I have textcomplete.js plugin, that search all content after #...., with this regex:
/\B#([\-+\w]*)$/
I return text in span like this:
<span contenteditable="false" class="highlight">#example</span>
And in my text in web page I see it like this:
#example |
( | -> place of my cursor )
If go back with cursor like this:
#example|
textcomplete fires and show me drop down, but i don't need it, so i try to find way, to change my regex, so that it doesn't find #text when it starts with
<span>#text
I try this, in regex online, it works:
/\B^(?!\>)#([\-+\w]*)$/
But in my project doesn't work.
I tried something like this, but this is a bit too hard for me
Can anyone help me?
EDITED:
In few words
I want to find regex expression , that finds this:
#exampletext
But don't find this:
<span>#exampletext
When cursor is behind last character of the word
You could use something like this:
(^(?!#).).+
Example and explanation: http://regex101.com/r/jL2fH0/2
What it does here is checks to make sure the string doesn't begin with an # before matching the rest. Note that in this example I've added the gmi flags - you may not want to use these given your requirements, they're just in there to demonstrate the regex working.
Note too that we have to do this workaround since JavaScript doesn't support negative lookbehinds.
I am currently programming a forum using only javascript (No JQuery please). I am doing very well, however, there is one issue I would love help with.
Currently I am getting the post from a database, assigning it to variable MainPost, and then attaching it to a div via a text node:
var theDiv = document.getElementById("MainBody");
var content = document.createTextNode(MainPost);
theDiv.appendChild(content);
This is working quite well, however, I would LOVE to be able to do this:
document.getElementById("MainBody").innerHTML += MainPost;
But I know this would allow people to use ANY html tag they want, even something like "script" followed by javascript code. This would be bad for business, obviously, but I do like the idea of allowing posters to use the "img" tag as well as the "a href" tags. Is there a way to somehow disable all tags except these two for the innerHTML?
Thank you all so much for any help you can offer.
Ok, the first thought that came to my mind when I read this question was to find a regular expression to exclude a specific string in a word. Simple search gave a lot of results from SO.
Starting point - To remove all the HTML tags from a string (from this answer):
var regex = /(<([^>]+)>)/ig
, body = "<p>test</p>"
, result = body.replace(regex, "");
console.log(result);
To exclude a string you would do something like this (again from all the source mentioned above):
(?!StringToBeExcluded)
Since you want to exlcude the <a href and <img tags. The suitable regex in your case could be:
(<(?![\/]?a)(?![\/]?img)([^>]+)>)
Explanation :
Think of it as three capturing groups in succession:
(?![\/]?a) : Negative Lookahead to assert that it is impossible to match the regex containing the string "a" prefixed by zero or one backslashes (Should take care of the a href tags)
(?![\/]?img) : Same as 1, just here it looks for the string "img". I don't know why I allowed the </img> tag. Yes, <img> doesn't have a closing tag. You could remove the [\/]? bit from it to fix this.
([^>]+) : Makes sure to not match > zero or one times to take care of tags that have opening and closing tags.
Now all these capture groups lie between < and >. You might want to try a regex demo that I've created incorporating these three capture groups to take care of ignoring all HTML elements except the image and link tags.
Sidenote - I haven't thoroughly given this regex a try. Feel free to play around with it and tweak it according to your needs. In any case, I hope this gets you started in the right direction.
I'm trying to figure out how to select dates (note: all dates, not just specific dates) in a paragraph using (I'm assuming) jQuery/Javascript.
To give an example, the website gets a bunch of text from a database, and in that text is included a date in the following format: (DD/MM/YYYY). I just want to highlight everytime that comes up, but I'm not sure how because sometimes the date can be 02/09/2014 or 13/10/2014, so I can't just search for a certain date and highlight it.
Any help is appreciated :) Thanks!
I think what you may be looking for is something like this. Here is a jsFiddle Example
$("div").html($("div").html().replace(/(\d{1,2}\/\d{1,2}\/\d{4})/gi, "<span style='background-color:yellow;'>$1</span>"));
Here is the same code above only on different lines for easier reading.
$("div")
.html(
$("div")
.html()
.replace(/(\d{1,2}\/\d{1,2}\/\d{4})/gi,
"<span style='background-color:yellow;'>$1</span>"
)
);
First we group the regEx with a left and right parentheses. This is now able to be referenced as parameter $1. We then look for the pattern we are seeking (do not forgot to add the gi at the end so that you look for all occurrences, not just the first one.
We then replace our find with a span tag so that we can style the contents, in this case a yellow background and we still want the date we found so we add in the $1 to put the date inside the span tags.
Hope this helps
Here's a super basic regex that will find 'datelike' number series:
\d{1,2}/\d{1,2}/\d{4}
Try it out here: http://regexhero.net/tester/
Using some text like "This is some text for the regex hero on 9/2/2014. I think for the most part it will work for what you are looking for on 9/3/2014."
In fact, here's some javascript to play with (using jquery):
http://jsfiddle.net/5z7bz4zm/2/
<div>
This is some text for the regex hero on 9/2/2014. I think for the most part it will work for what you are looking for on 9/3/2014.
</div>
$(document).ready(function() {
$("div").text($("div").text().replace(/\d{1,2}\/\d{1,2}\/\d{4}/, "<span>caught ya</span>"));
});
can you please tell me how to remove the span tag using jquery.
INPUT
<span class="abc">PQR </span>
OUTPUT
PQR
I done before but don't remember I think I used regex or replace .:(
Second
How to replace   by a space(" ") ?
I used like that but not work.
replace(/ /g,'');
For the first part, Tim's answer is great. $('.abd').contents().unwrap().
For the second part, please do it properly. is an html-encoded special characters (non-breakable space), but there are tons of other characters you can encounter (like é for é).
Unfortunately there's no built-in standard html decode function, but you can create one with jquery like this:
function htmlDecode(encodedText) {
return $("<div>").html(encodedText).text();
}
For the first part, you can use $('.abc').contents().unwrap()
For the second part see jods answer :)