I'm trying to check if a string contains this character `.
And if the character is found, to wrap that string between <div>.
For example:
`this is it
should become:
<div>this is it</div>
And I've tried to do it but it seem to not work:
let arr = "`this is it";
if (arr.includes('`')) {
arr = arr.replace(/\`(\w+)\`/g, '<div>$1</div>');
}
Any ideas?
You can use
arr.replace(/`([^`]+)`?/g, '<div>$1</div>')
The regex matches
` - a backtick
([^`]+) - one or more chars other than backtick
`? - an optional backtick
JavaScript demo
const arrs = ["`test` is `here`","`this is it"];
const regex = /`([^`]+)`?/g;
for (const arr of arrs) {
console.log(arr, '=>', arr.replace(regex, '<div>$1</div>'));
}
I presume that the backtick should only appear at the beginning of the line. If it is also needed at the end, add another one before the $ in the regex.
I also presume that your string is multiline, and any line can start with a backtick. If not, remove the m flag.
If there can be more than one backtick-delimited substrings in a line, make the * quantifier non-greedy with ? and remove the ^ and $ assertions. If such substring can span several lines, also add s flag.
let arr = "`this is it";
arr = arr.replace(/^`(.+)$/mg, '<div>$1</div>');
console.log(arr)
Related
So I have this (example) string: 1234VAR239582358X
And I want to get what's in between VAR and X. I can easily replace it using .replace(/VAR.*X/, "replacement");
But, how would I get the /VAR.*X/as a variable?
I think what you are looking for might be
string.match(/VAR(.*)X/)[1]
The brackets around the .* mark a group. Those groups are returned inside the Array that match creates :)
If you want to only replace what's in between "VAR" and "X" it would be
string.replace(/VAR(.*)X/, "VAR" + "replacement" + "X");
Or more generic:
string.replace(/(VAR).*(X)/, "$1replacement$2");
You can try use the RegExp class, new RegExp(`${VAR}.*X`)
You can store it as variable like this,
const pattern = "VAR.*X";
const reg = new RegExp(pattern);
Then use,
.replace(reg, "replacement");
If you
want to get what's in between VAR and X
then using .* would do the job for the given example string.
But note that is will match until the end of the string, and then backtrack to the first occurrence of X it can match, being the last occurrence of the X char in the string and possible match too much.
If you want to match only the digits, you can match 1+ digits in a capture group using VAR(\d+)X
const regex = /VAR(\d+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
Or you can match until the first occurrence of an X char using a negated character class VAR([^\r\nX]+)X
const regex = /VAR([^\r\nX]+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
Example data expected output
sds-rwewr-dddd-cash0-bbb cash0
rrse-cash1-nonre cash1
loan-snk-cash2-ssdd cash2
garb-cash3-dfgfd cash3
loan-unwan-cash4-something cash4
The common pattern is here, need to extract a few chars before the last hyphen of given string.
var regex1= /.*(?=(?:-[^-]*){1}$)/g ; //output will be "ds-rwewr-dddd-cash0" from "sds-rwewr-dddd-cash0-bbb "
var regex2 = /\w[^-]*$/g ; //output will be "cash0" from "ds-rwewr-dddd-cash0"
var res =regex2.exec(regex1.exec(sds-rwewr-dddd-cash0-bbb)) //output will cash0
Although above nested regex is working as expected but may not be optimize one. So any help will be appreciated for optimized regex
You can use
/\w+(?=-[^-]*$)/
If the part before the last hyphen can contain chars other than word chars, keep using \w[^-]*: /\w[^-]*(?=-[^-]*$)/. If you do not need to check the first char of your match, simply use /[^-]+(?=-[^-]*$)/.
See the regex demo.
Details:
\w+ - one or more word chars
(?=-[^-]*$) - that must be followed with - and then zero or more chars other than - till the end of string.
JavaScript demo
const texts = ['sds-rwewr-dddd-cash0-bbb','rrse-cash1-nonre','loan-snk-cash2-ssdd','garb-cash3-dfgfd','loan-unwan-cash4-something'];
const regex = /\w+(?=-[^-]*$)/;
for (var text of texts) {
console.log(text, '=>', text.match(regex)?.[0]);
}
I want to replace {r-group1} with "REPLACED" but leave the , where it is.
So, the string
var string = "{r-group1, }foo bar"
should output: "REPLACED, foo bar"
Using a negative lookahead, I tried adding a preceding (?![,]) group to leave the comma alone:
var replaced = string.replace(^(?:(?![,]){r-group1\})+$, 'REPLACED');
But it returns the same string. There are no matches to replace.
The same goes for a preceding comma:
var string = "foo bar{r-, group1}"
This should output: "foo bar, REPLACED"
You could do the replacement without a lookahead. You could match the curly braces and the content that comes before and after it except a comma using a negated character class [^,}]+ and capture the comma with optional whitespace chars in a capturing group.
In the replacement use the capturing groups $1REPLACED$2
Credits to #Nick for the updated pattern.
{r-(,?\s*)[^,}]+(,?\s*)}
Regex demo
const regex = /{r-(,?\s*)[^,}]+(,?\s*)}/g;
const str = `{r-group1, }foo bar`;
const subst = `$1REPLACED$2`;
const result = str.replace(regex, subst);
console.log(result);
How i can select RQR-1BN6Q360090-0001 (without quotes) using Regex in below -
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
I tried this but it does not work
RptNum=([A-Za-z]+)$
You may use
/RptNum=([\w-]+)/
The pattern will match RptNum= and then capture 1 or more occurrences of word chars (letters, digits and _) or hyphens. See the regex demo and the regex graph:
Note that
/RptNum=([A-Z0-9-]+)/
might be a more restrictive pattern that should work, too. It does not match _ and lowercase letters.
In JS, use it with String#match() and grab the second array item upon a match:
var s = 'Object moved to here';
var m = s.match(/RptNum=([\w-]+)/);
if (m) {
console.log(m[1]);
}
Here, we can also use an expression that collects the new lines, such as:
[\s\S]*RptNum=(.+?)"[\s\S]*
[\w\W]*RptNum=(.+?)"[\w\W]*
[\d\D]*RptNum=(.+?)"[\d\D]*
and our desired output is saved in (.+?).
Test
const regex = /[\s\S]*RptNum=(.+?)"[\s\S]*/gm;
const str = `<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
Demo
RegEx
If this expression wasn't desired, it can be modified/changed in regex101.com.
RegEx Circuit
jex.im visualizes regular expressions:
const text = 'RptNum=RQR-1BN6Q360090-0001';
console.log(text.match(/RptNum=.*/).map(m => m.match(/RptNum=.*/)[0])[0].split('RptNum=')[1]);
I suppose that works
I have a string received from backend, and I need to extract hashtags. The tags are written in one of these two forms
type 1. #World is a #good #place to #live.
type 2. #World#place#live.
I managed to extract from first type by : str.replace(/#(\S*)/g
how can i change the second format to space seperated tags as well as format one?
basically i want format two to be converted from
#World#place#live.
to
#World #place #live.
You can use String.match, with regex #\w+:
var str = `
type 1. #World is a #good #place to #live.
type 2. #World#place#live.`
var matches = str.match(/#\w+/g)
console.log(matches)
\w+ matches any word character [a-zA-Z0-9_] more than once, so you might want to tweak that.
Once you have the matches in an array you can rearrange them to your likes.
The pattern #(\S*) will match a # followed by 0+ times a non whitespace character in a captured group. That would match a single # as well. The string #World#place#live. contains no whitespace character so the whole string will be matched.
You could match them instead by using a negated character class. Match #, followed by a negated character class that matches not a # or a whitespace character.
#[^#\s]+
Regex demo
const strings = [
"#World is a #good #place to #live.",
"#World#place#live."
];
let pattern = /#[^#\s]+/g;
strings.forEach(s => {
console.log(s.match(pattern));
});
How about that using regex /#([\w]+\b)/gm and join by space like below to extract #hastags from your string? OR you can use str.replace(/\b#[^\s#]+/g, " $&") as commented by #Wiktor
function findHashTags(str) {
var regex = /#([\w]+\b)/gm;
var matches = [];
var match;
while ((match = regex.exec(str))) {
matches.push(match[0]);
}
return matches;
}
let str1 = "#World is a #good #place to #live."
let str2 = "#World#place#live";
let res1 = findHashTags(str1);
let res2 = findHashTags(str2);
console.log(res1.join(' '));
console.log(res2.join(' '));