Regex in JavaScript is not matching a string? - javascript

I have this JavaScript code:
var textareas = document.getElementsByTagName('textarea');
var content = textareas[0].value;
var reg = new RegExp(/^.*[[]#.+#[]].*$/mgi);
var res = content.match(reg); // always null
The content var contains a long multiline string that contains patterns like [#some text goes here#]. I tested the regex with some online testing tools and it works against the string. Using the regex in JavaScript fails though - any idea why?
Thanks!

How about this?
var content = 'foo\nhead [#some text goes here#] tail\nbar';
var reg = new RegExp(/\[#.+#\]/mgi);
var res = content.match(reg);
On execution, res contains the string '[#some text goes here#]'.
Note that I have escaped [ and ]. If they are not escaped, anything enclosed within them forms a character class.

You used [[] to escape [, which is fine, but you can't use []] to escape ] because it the first ] ends the character class in the regex. This works fine:
/^.*\[#.+#\].*$/mgi
In the case that you only want the single block and not the entire line, use:
/\[#.+#\]/mgi

This should capture the text between hashes (e.g., "some text here"):
var reg = /[^\[]*\[#([^\#]+)#\]/gims

Related

How do I pass a variable into regex with Node js?

So basically, I have a regular expression which is
var regex1 = /10661\" class=\"fauxBlockLink-linkRow u-concealed\">([\s\S]*?)<\/a>/;
var result=text.match(regex1);
user_activity = result[1].replace(/\s/g, "")
console.log(user_activity);
What I'm trying to do is this
var number = 1234;
var regex1 = /${number}\" class=\"fauxBlockLink-linkRow u-concealed\">([\s\S]*?)<\/a>/;
but it is not working, and when I tried with RegExp, I kept getting errors.
You can use RegExp to create regexp from a string and use variables in that string.
var number = 1234;
var regex1 = new RegExp(`${number}aa`);
console.log("1234aa".match(regex1));
You can build the regex string with templates and/or string addition and then pass it to the RegExp constructor. One key in doing that is to get the escaping correct as you need an extra level of escaping for backslashes because the interpretation of the string takes one level of backslash, but you need one to survive as it gets to the RegExp contructor. Here's a working example:
function match(number, str) {
let r = new RegExp(`${number}" class="fauxBlockLink-linkRow u-concealed">([\\s\\S]*?)<\\/a>`);
return str.match(r);
}
const exampleHTML = 'Some link text';
console.log(match(1234, exampleHTML));
Note, using regex to match HTML like this becomes very order-sensitive (whereas the HTML itself isn't order-sensitive). And, your regex requires exactly one space between classes which HTML doesn't. If the class names were in a slightly different order or spacing different in the <a> tag, then it would not match. Depending upon what you're really trying to do, there may be better ways to parse and use the HTML that isn't order-sensitive.
I solved it with the method of Adem,
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
var number = 1234;
var firstPart = `<a href="/forum/search/member?user_id=${number}" class="fauxBlockLink-linkRow u-concealed">`
var regexpString = escapeRegExp(firstPart) + '([\\s\\S]*?)' + escapeRegExp('</a>');
console.log(regexpString)
var sample = ` `
var regex1 = new RegExp(regexpString);
console.log(sample.match(regex1));
in the first place the issue was actually the way I was reading the file, the data I was applying the match on, was undefined.

javascript regex to find only numbers with hyphen from a string content

In Javascript, from a string like this, I am trying to extract only the number with a hyphen. i.e. 67-64-1 and 35554-44-04. Sometimes there could be more hyphens.
The solvent 67-64-1 is not compatible with 35554-44-04
I tried different regex but not able to get it correctly. For example, this regex gets only the first value.
var msg = 'The solvent 67-64-1 is not compatible with 35554-44-04';
//var regex = /\d+\-?/;
var regex = /(?:\d*-\d*-\d*)/;
var res = msg.match(regex);
console.log(res);
You just need to add the g (global) flag to your regex to match more than once in the string. Note that you should use \d+, not \d*, so that you don't match something like '3--4'. To allow for processing numbers with more hyphens, we use a repeating -\d+ group after the first \d+:
var msg = 'The solvent 67-64-1 is not compatible with 23-35554-44-04 but is compatible with 1-23';
var regex = /\d+(?:-\d+)+/g;
var res = msg.match(regex);
console.log(res);
It gives only first because regex work for first element to test
// g give globel access to find all
var regex = /(?:\d*-\d*-\d*)/g;

How to convert Java Regex to JavaScript regex?

How to convert regex java in regex javascript
I have for example the text :
#hello some text #Home
My Java regex is
String regex = "[#]+[A-Za-z0-9-_]+\\b";
Pattern tagMatcher = Pattern.compile("[#]+[A-Za-z0-9-_]+\\b");
the result is
#hello and #Home
My Javascript code is :
var myRegExp = new RegExp("[#]+[A-Za-z0-9-_]+\\b");
var tagMatcher = text.match(myRegExp);
but the result is :
#hello
How can I solve the problem?
Where is my error?
Missing global flag g to get the whole set of matches.
var text = "#hello some text #Home";
var myRegExp = new RegExp("[#]+[A-Za-z0-9-_]+\\b", "g");
var tagMatcher = text.match(myRegExp);
console.log(tagMatcher)
Like #JordanRunning mentioned, you can use Regex literal as follow, as well as a shorter approach:
var text = "#hello some text #Home";
var tagMatcher = text.match(/#+[\w-]+\b/g);
console.log(tagMatcher)
Advanced searching with flags
Regular expressions have five optional flags that allow for global and case insensitive searching. These flags can be used separately or together in any order, and are included as part of the regular expression.

Javascript RegEx contains

I'm using Javascript RegEx to compare if a string matches a standart format.
I have this variable called inputName, which has the following format (sample):
input[name='data[product][tool_team]']
And what I want to achieve with Javascript's regex is to determine if the string has the following but contains _team in between those brackets.
I tried the following:
var inputName = "input[name='data[product][tool_team]']";
var teamPattern = /\input[name='data[product][[_team]]']/g;
var matches = inputName.match(teamPattern);
console.log(matches);
I just get null with the result I gave as an example.
To be honest, RegEx isn't really my area, so I suppose it's wrong.
A couple of things:
You need to escape [ and ] as they have special meaning in regex
You need .* (or perhaps [^[]*) in front of _team if you want to allow anything there ([^[]* means "anything but a [ repeated zero or more times)
Example if you just want to know if it matches:
var string = "input[name='data[product][tool_team]']";
var teamPattern = /input\[name='data\[product\]\[[^[]*_team\]'\]/;
console.log(teamPattern.test(string));
Example if you need to capture the xyz_team bit:
var string = "input[name='data[product][tool_team]']";
var teamPattern = /input\[name='data\[product\]\[([^[]*_team)\]'\]/;
var match = string.match(teamPattern);
console.log(match ? match[1] : "no match");
If you are trying to check for DOM elements you can use attribute contains or attribute equals selector
document.querySelectorAll("input[name*='[_team]']")

regular expression to remove comment javascript

I am using below regular expression to remove comments from string
<\!{1}\-{2}(.*?)\-{2}\s*>
This is working fine except for mult-iline string
var search = '<\!{1}\-{2}(.*?)\-{2}\s*>';
var re = new RegExp(search, "gm");
var subject = <multi-line string>;
result = subject.replace(re, '');
what should I do to get it working with multiline strings
. does not allow linebreaks.
This one should work:
^(<\!\-{2})((.|\s)*?)\-{2}>$
Fix:
<!--[\S\s]*?-->
I removed the \s at the beginning and the end of the expression and added it in the middle so multiline-comments are allowed.
But you shoud have a look at BartKs comment ;)
regards

Categories

Resources