How to replace HTML compoment only use Regular Expression - javascript

I am currently working on some server side code to parse HTML. I have following html string:
<div class="rte-style-maintainer rte-pre-wrap" style="white-space: pre-wrap; font-size: small; >This is a test for link {<a spellcheck="false" destination="rte:bind" data-destination="rte:bind">ABCD 156782053 </a>}</div>
And want to replace the content inside the bracket {} with
<a href="ABCD 156782053">ABCD 156782053 </a>
I am new to the regular expression. How can I get the "ABCD 156782053" from the bracket using regular expression? And replace the content inside bracket with new value?
Thanks

First of all, your HTML syntax is wrong. Some closing quotes are missing.
Anyway, the syntax of this expression is that:
/{(.*?)}/g
Here is the test link: https://regexr.com/542vj

Related

Regular Expression

I've needed to display an alert in case there's a text input includes a double-quote which isn't followed by a backslash. So I used 'negative lookbehind' regular expression and achieved that goal.
text.innerHTML.match(/(?<!\\)\"/);
" -> Alert
\" -> OK
However, I found an issue that when users put an indent into text box, the WYSIWYG (Quill) generates a class named "ql-indent-N (indent level starting from 1)" which triggers an alert by " detection.
Thus, I added another exception to the original regular expression like below.
text.innerHTML.match(/(?<!\\)(?<!class=)\"/);
But it didn't work so I tried some tests in console, and saw that
it works fine when I just put
class=" -> OK
while, it does not work when it's inside real tag like
<p class="ql-indent-1"> text </p> -> Alert
How can I make a lookbehind reg exp working fine with those <p class=" ...">? Or any other generous suggestion to achieve the same goal — Displaying an alert to double-quotes not followed by a backslash nor by <p class=" ...">? Below is a basic structure of the textbox.
<div class="ql-editor" data-gramm="false" contenteditable="true">
<p>text</p>
</div>
Dealing Quill's delta format is very complicated.
As mentioned in the comment, you could refer to the element innerText rather than its innerHTML in order to ignore any tag inserted by the WYSIWYG editor.
Example (here I am using RegExp.prototype.test() rather than RegExp.prototype.match())
const qEditor = document.querySelector('.ql-editor');
const re = /(?<!\\)"/gm;
qEditor.addEventListener('input', () => {
if (re.test(qEditor.innerText)){
window.alert('All double-quotes (") must be escaped (\\")');
}
})
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<div id="editor" class="ql-editor" data-gramm="false" contenteditable="true">
<p>text</p>
</div>
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<script>
var quill = new Quill('#editor', {
theme: 'snow'
});
</script>

Regex cutting down a specific character

I have this HTML tag <a href="abc> google </a>, how can i put the " after the letter c using regular expression
HTML: <a href="abc> google </a>
Regex: /\=\s*["“'”](.*?)[^“"'”]\s*\>/g
Replace: ="$1">
https://regex101.com/r/1FQods/1
https://jsfiddle.net/liev04/6n038nvm/
How about
str.replace(/href="[^\s>"]+/, function(match) { return match+'"' });
I suggest the following:
str.replace(/=\s*["']([^"']*?)\s*?(?=>)/g,'="\1"');
This should work also in cases where the second " exists already. It also allows for blanks between the = and the beginning of the string.
See here for a demo: https://regex101.com/r/xo52ka/1
Another issue might be cases like:
<a href="abc def > google </a>
My Solution will turn that into
google
But, of course, this solution has its limitations and is by far not watertight. It will only work on the last attribute of each tag (because of the lookahead (?=>) in the regexp).

Transform plain text as a css value with javascript

I'm making a style guide and I have disabled css in pre markup that I'm trying to apply as valid css to example boxes above.
Easier to understand with markup (please don't mind the weird indentation, it's done on purpose to simplify rendering. Also "defaut" is the french word for "default") :
<div id="styleguide" class="field-style">
<div class="colored">
</div>
<pre><code class="language-less">
#defaut: #000;
</code></pre>
<div class="colored">
</div>
<pre><code class="language-less">
#defaut: #e55240;
</code></pre>
<div class="colored">
</div>
<pre><code class="language-less">
#defaut: #fff;
</code></pre>
</div>
I tried several variations but it doesn't work. Here is my latest attempt. In here I'm trying to select via regex everything up to and including '#', and delete it. Then I get the numbers and put them in background style. You could say I should filter directly to only select numerical values via regex, but it didnt't work either and I don't know why
$('.field-style .colored').each(function() {
var $this = $(this);
$this.css(
'background', '#' +
$this
.next('pre')
.children('code')
.text()
.replace('/^(.*?\\#)|;/', '')
);
You could try to use the colon to split the text and take the second value resulting from it, then removing the semicolon:
$(this).css(
'background',
$(this).next().text()
.split(':')[1]
.trim()
.replace(';','')
);
Apart from ensuring that your target divs are either not empty or have some height, you need to:
either replace your prefix and trim the textContent to get rid of trailing spaces/breaks along with getting rid of the last ;:
$this.next().find('code').text().replace('#defaut: ', '').trim().slice(0, -1)
or split on : and rest on the second element of the resulting array:
$this.next().find('code').text().split(':')[1].trim().slice(0, -1)
Demo:
$('.colored').each(function() {
var $this = $(this),
prop = $this.next().find('code').text().replace('#defaut: ', '').trim().slice(0, -1)
;
$this.css({'background-color': prop });
});
div.colored { height: 16px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="styleguide" class="field-style">
<div class="colored">First</div>
<pre><code class="language-less">
#defaut: #f00;
</code></pre>
<div class="colored">Second</div>
<pre><code class="language-less">
#defaut: #0f0;
</code></pre>
<div class="colored">Third</div>
<pre><code class="language-less">
#defaut: #00f;
</code></pre>
</div>
There's a two issues with your regular expression:
There's a newline between the code tag and #defaut which will not be matched by the .. From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions:
(The decimal point) matches any single character except the newline character.
Use trim() to get rid of leading and trailing space.
The regular expression must not be enclosed in quotes, otherwise it will be treated as a regular string. Use replace(/^(.*?\\#)|;/) instead.
As a further note it might be better to get the color value by extracting it instead of deleting everything else around it:
$this
.next('pre')
.children('code')
.text().match(/#defaut:\s*(#.+?);/)[1]
This regular expression will look for "#defaut:" potentially followed whitespace, then followed by a color value terminated by a semicolon and extract the color value. An added avantage is that this solution won't break as easily in case you have to add more data inside the <code> tag or change the formatting.

Javascript: Regex of a HTML h4 tag

i have a variable "html" with an HTML code.
I need to extract:
<h4 class="search-results-count">ANY TEXT THAT GOES HERE</h4>
but i can't figure how to do that with regex or another tecnique
You can extract the innerHTML like
document.querySelector('.search-results-count').innerHTML
You should not parse html with regex
You can use the following regex: (not recommended)
<h4[^>]*>([^<]*)<\/h4>
And extract group 1.. $1
See demo

Passing variable with single quote in javascript

I have an onClick call on a link:
<a onClick="fomateName('Andrew Dsouza')"> //this is working good
The problem is the variable inside fomateName would contain single quotes and my fomateName Takes a variable like
var a='Andrew D'souza'. Need to format a variable present with single quote Ex;
<a onClick="fomateName('a')"> which turns to
<a onClick="fomateName('Andrew D'souza')"> //this is not working ,because present of single quote
Any Idea how to pass text with proper quotes in a javascript.
with single quote not the name actually
Try:
<a onClick="fomateName('Andrew D\'souza')"> <!-- this will work -->
\ use backslashes to escape '
Lets say if you have function like this =>
function fomateName(txt){
alert(txt);
}
and invoking it from anchor =>
<a onClick="fomateName('Andrew D\'souza')"> <!-- this will alert "Andrew D'souza" -->
Escape the quote with backslashes.
<a onClick="fomateName('Andrew D\'souza')">
//this is not working ,because present of single quote
You can wrap it in double quotes like so:
<a onClick="fomateName("Andrew D'souza")"> //this is not working ,because present of single quote
Never mind, just realized it already has double quotes, yeah use backslash for escape like so:
<a onClick="fomateName('Andrew D\'souza')">
Try this. Use backslash - It will escape the quote breaks
<a onClick="fomateName('Andrew D\'souza')">
You can use escape character
<a onclick="formateName('AdrewD\'souza')">
You can escape the quote with a backslash..
fomateName('Andrew D\'souza');
This should work anyway:
var name = "Andrew D'souza";
fomateName(name);

Categories

Resources