How to prefix certain characters in a string with regex? - javascript

Suppose the following,
const str = `
hello!
proceed - click button below.
`
I need to prefix certain characters with \\. In this case, I need the following result:
`
hello\\!
proceed \\- click button below\\.
`
Currently, I am doing this:
const str = `
hello!
proceed - click button below.
`.replace(/!/gm, '\\!').replace(/-/gm, '\\-').replace(/\./gm, '\\.')
console.log(str);
Seems messy. Any better way to do it?

Use capture groups. Inside group () have the characters you'd like to replace [!\-.] and then in the replace reference the group $1. You also need to add extra \\ to get 2 in the final output
const str = `
hello!
proceed - click button below.
`.replace(/([!\-.])/gm, '\\\\$1')
console.log(str)

Related

JavaScript function to identify URL and make them clickable

I have a requirement , my client send me a string. for the links he is sending link title in squre brackets and link with bracket. like below,
[Google](https://www.google.com/)
I need get that value and make it clickable Google . adding like below and replace that to the original text.
' + url + ''
can anyone suggest better way of doing this with JavaScript regex.
Looks like Markdown formatting, so you could use a markdown library like Marked to parse and render it:
const s = '[Google](https://www.google.com/) ';
document.getElementById('content').innerHTML = marked(s);
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<div id="content"></div>
Can be done with String replace function.
Regex: /\[(.*)\]\s*\((.*)\)/g
Replacer: $1
const str = `Lorem ipsum. [Google](https://www.google.com/). Sample text.`
const output = replaceWithLinks(str);
console.log(output);
function replaceWithLinks(str) {
return str.replace(/\[(.*)\]\s*\((.*)\)/g, '$1')
}
In HTML file:
<h1 id="header"></h1>
In Js File:
const myString = "[Google](https://www.google.com/)";
const show = myString.match(/\[(.*?)\]/); // it return two things. The first is with bracket and the second one is without bracket you have to use without bracket.
const url = myString.match(/\((.*?)\)/);
document.getElementById("header").innerHTML = `${show[1]}`;
You have to use regular expression. To get information about regular expression read MDN.
Get the first index value and show it to the UI.
Regexp is very handy for this purpose. just copy below code to F12 console for a preview
"text before [Google](https://www.google.com/) and after".replace(/\[(.*?)\]\((.*?)\)/gm, '$1')
ps: the code copy from a simple markdown parser

Javascript strip using regex to get before and after an a tag in string

I have this string from the server
15 Steps is mandatory and must be completed by 14/02/2021: click <a href='http://example.co.uk/training/CRU0007'>here</a> to book/start your learning.
I need to get 2 values
15 Steps is mandatory and must be completed by 14/02/2021: click
&
to book/start your learning.
When I tried this before I had a string wrapped in : and ; and the below code worked
var arrStr = newsText.split(/[:;]/);
but if I try
var arrStr = newsText.split(/[<a></a>]/);
I get a jumbled mess.
So I decided to try and use regex and got this far
const linkRx = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/;
var arrStr = newsText.split(linkRx);
But this leaves the
>here</a> in the final part
So how do I edit the regex to get the rest of the a tag. I've searched through lots of answers but they don't seem to get the whole tag.
I would use the following regex.
The purpose is to get wathever is before and after the <anything></anything>.
const str = `15 Steps is mandatory and must be completed by 14/02/2021: click <a href='http://example.co.uk/training/CRU0007'>here</a> to book/start your learning.`;
const regex = /(.*?)(?:<.*?>.*?<\/.*?>)(.*)/gm;
const [,
partA,
partB,
] = regex.exec(str);
console.log('PartA :', partA);
console.log('PartB :', partB);
Based on your attempt, could you please try following, Online demo is: Online regex demo
var newsText = `15 Steps is mandatory and must be completed by 14/02/2021: click <a href='http://example.co.uk/training/CRU0007'>here</a> to book/start your learning.`
var arrStr = newsText.split(/\s*<a\s+href=[^>]*>[^>]*<\/a>\s*/);
console.log(arrStr);
Explanation: if matches 0+ whitespaces followed by a <href= tag and closing </a> tag followed by 0+ whitespaces.

Multiple quotes in comments with replace

I need to transform this:
[quote=mvneobux]My first comment[/quote]
I liked your comment.
In that:
<div class="quote">
<div class="author">mvneobux:</div>
My first comment.
</div>
I liked your comment.
the solution date in another topic works perfectly when there is only one quote. but two quotes or more don't work.
The current code is as follows
comment.replace(/\[quote=(.+?)\](.+?)\[\/quote\]/, '<div class="quote"><div class="author"> $1 </div> $2 </div>');
but in the following scenario the result is broken:
[quote=username2][quote=mvneobux]interessante e bom continue[/quote][/quote]
How can I solve? remembering that there may be several quotes within each other. How could I take each one separately?
Instead of using .*? to match the content in the middle, match anything but [quote=SOMETHING] with ((?:(?!\[quote).)*?). Then, replace one at a time, until there are no more matches:
let str = `[quote=mvneobux][quote=charlote]parabens pelo relato[/quote] legal seu relato[/quote]interessante`;
const pattern = /\[quote=([^\]]+)\]((?:(?!\[quote).)*?)\[\/quote\]/;
while (pattern.test(str)) {
str = str.replace(pattern, '<div class="quote"><div class="author">$1</div>$2</div>');
}
console.log(str);
Another options is just creating a simpler RegEx expression and use a simple replace in combination like
let result = `[quote=mvneobux]My first comment[/quote]
I liked your comment.`
.replace(/\[quote=(.+?)\]/,"<div class='author'>$1<div>")
.replace("[/quote]", "<div>");
console.log(result);

Extracting text that sits between two pairs of special characters

I am trying to extract a string from a sentence that is embedded within the HTML tags <b></b> that are also embedded within parenthesis ( ).
I can do this with the following code
const regExp = /\(([^)]+)\)/
// fetches the string within parentheses
let string = regExp.exec('This is some (<b>super cool</b>) text I have here')
// output = '<b>super cool</b>
// removes the html tags
let string2 = string.replace(/<[^>]*>?/gm, '')
// output = 'super cool'
The problem is I sometimes have sentences with multiple sets of parentheses. The code above will only extract the first instance of parentheses, and they may or may not be within the <b></b> tags
i.e., the string
This is (some) (<b>super cool</b>) text I have (here)
will return some using the same code above, but what I want is to return super cool
How can I traverse the entire string to extract only the text that sits within (<b> and </b>)?
EDIT
I forgot to mention (apologies), there may be text that comes in between the closing tag </b> and the closing parenthesis ). For example
This is some (<b>super cool</b> groovy) text I have here
Which adds a bit of complexity (otherwise I could use split() and pop()
You could use this regExp instead: /(?<=\(<b>)(.*?)(?=<\/b>\))/ which will capture everything between the first (<b> and </b>) encountered.
If you want to capture all instances, just add the global flag /g : /(?<=\(<b>)(.*?)(?=<\/b>\))/g
Also with this method you won't need to do a string.replace() afterwards, saving you another operation.
const regExp = /(?<=\(<b>)(.*?)(?=<\/b>\))/
const str = 'This is some (<b>super cool</b>) text I have here'
console.log(str.match(regExp)[0])
// --> super cool
EDIT: Following OP's edit, if some text can come between the closing tag </b> and the closing ), just change your regExp to: /(?<=\(<b>)(.*?)(?=\))/, which will capture everything between the first (<b> and ) encountered.
But then you will also need to string.replace('</b>', '') to remove the closing </b> tag.
const regExp = /(?<=\(<b>)(.*?)(?=\))/
const str = 'This is some (<b>super cool</b> groovy) text I have here'
console.log(str.match(regExp)[0].replace('</b>', ''))
// --> super cool groovy
This works for me try like this instead of regex use split
const string = 'This is (some) (<b>super cool</b>) text I have (here)';
const str = string.split('<b>').pop().split('</b>')[0];
console.log(str);

Replace anything between paragraph tags if it is a html tag

I need to remove empty paragraphs from a string which is being pasted into a html textarea. I have this as a regular expression to do that.
var reg = /\<p( [a-zA-Z]*=((\"[^\"]*\")|(\'[^\']*\')))*\>\<\/p\>/g;
and it works okay. But, some of the data being pasted contains paragraphs that look like this.
<p><b></b></p>
So the regular expression does not work - as the paragraph, although it contains no actual text, does contain html tags.
Can anyone tell me please now to modify my regular expression so that it will not only replace paragraphs with no content with an empty string, but will also replace paragraphs where the only content is html tags.
At the moment text like this.
<p style="margin:0px;"></p>
<p>Fred</p>
<p style="margin-left:10px;"></p>
<p><b></b></p>
<p>Jim</p>
is being modified so it then becomes
<p>Fred></p>
<p><b></b></p>
<p>Jim</p>
I need it to become
<p>Fred</p>
<p>Jim</p>
You can try this:
<p[^>]*>(?:\s*<(\w+)>\s*<\/\1>\s*|\s*)<\/p>
and replace by empty
Regex Demo
const regex = /<p[^>]*>(?:\s*<(\w+)>\s*<\/\1>\s*|\s*)<\/p>/g;
const str = `<p style="margin:0px;"></p>
<p>Fred</p>
<p style="margin-left:10px;"></p>
<p><b></b></p>
<p>Jim</p>`;
const subst = ``;
const result = str.replace(regex, subst);
console.log(result);

Categories

Resources