javascript find and replace a dynamic pattern in a string - javascript

I have a dynamic pattern that I have been using the code below to find
var matcher = new RegExp("%" + dynamicnumber + ":", "g");
var found = matcher.test(textinput);
I need the pattern to have a new requirement, which is to include an additional trailing 5 characters of either y or n. And then delete it or replace it with a '' (nothing).
I tried this syntax for the pattern, but obviously it does not work.
var matcher = new RegExp("%" + dynamicnumber + ":" + /([yn]{5})/, "g");
Any tip is appreciated
TIA.

You should only pass the regex string into the RegExp c'tor :
var re = new RegExp("%" + number + ":" + "([yn]{5})", "g");

var matcher = new RegExp("(%" + number + ":)([yn]{5})", "g");
Then replace it with the contents of the first capture group.

Use quotes instead of slashes:
var matcher = new RegExp("%" + number + ":([yn]{5})", "g");
Also, make sure that dynamicnumber or number are valid RegExps. special characters have to be prefixed by a double slash, \\, a literal double slash has to be written as four slashes: \\\\.

Related

JS Regexp - how to find text in a string

There is some text, exp: "The string class is an instantiation of the basic_string class template that uses char".
I need to find the text - "basic_string", but if there is no word "the" in front of him.
If use negative lookbehind, it was be:
(?<!\sthe)\s+basic_string
But javascript not understand negative lookbehind, what to do?
If the only allowed character between "the" and "basic_string" is the white-space:
([^e\s]|[^h]e|[^t]he)\s+basic_string
You can use xregexp library to get advanced regex features like lookbehind in Javascript.
Alternatively you can use alternation and capture group as a workaround:
var s = 'The string class is an instantiation of the basic_string class template that uses char';
var kw = s.match(/\bthe basic_string\b|(\bbasic_string\b)/)[1];
// undefined
s = 'instantiation of basic_string class template'
kw = s.match(/\bthe basic_string\b|(\bbasic_string\b)/)[1]
//=> "basic_string"
In this regex, captured group #1 will only be populated if bbasic_string isn't preceded by word the.
You can use RegExp /(the)(?\sbasic_string)/ or new RegExp("(" + before + ")(?=" + match + ")") to match "the" if followed by " basic_string", .match() to retrieve .index of matched string, .slice() to get "basic_string"
var str = "The string class is an instantiation of the basic_string class template that uses char";
var before = "the";
var match = " basic_string";
var index = str.match(new RegExp("(" + before + ")(?=" + match + ")")).index
+ before.length + 1;
console.log(str.slice(index, index + match.length));
The easiest way to emulate the negative lookbehind is via an optional capturing group, and check if the group participated in the match:
/(\bthe)?\s+basic_string/g
^^^^^^^^
See this JS demo:
var s = 'The string class is an instantiation of the basic_string class template that uses char, not basic_string.';
var re = /(\bthe)?(\s+basic_string)/gi;
var res = s.replace(re, function(match, group1, group2) {
return group1 ? match : "<b>" + group2 + "</b>";
});
document.body.innerHTML = res;

Regex to match markdown image pattern with the given filename

I want to replace a markdown image pattern with the given filename in the textarea with an empty string.
So the pattern is ![alt](http://somehost/uploads/filename.jpg)
This is the code I have now:
var content = target.val();
var fileName = someDynamicValue;
var regex = new RegExp(RegExp.escape('![') + '.*' + RegExp.escape(']') + RegExp.escape('(') + '.*' + RegExp.escape(fileName) + RegExp.escape(')'), 'i');
var found = regex.exec(content);
var newContent = content.replace(regex, "");
target.val(newContent);
RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
For example var fileName = filename.jpg. Then I need to match ![alt](http://somehost/uploads/filename.jpg) and replace it with an empty string.
Everything works great if the content includes one image. But if there are more then one, for example:
Some text ![alt](http://somehost/uploads/filename.jpg) some text ![alt2](http://somehost/uploads/filename2.jpg) more text.
then var found includes ![alt](http://somehost/uploads/filename.jpg)![alt2](http://somehost/uploads/filename2.jpg), but I need to match only ![alt](http://somehost/uploads/filename.jpg).
What regex I need in this case?
Use non-greedy quantifiers will do:
!\[(.*?)\]\((.*?)\)
You can check it out online: https://regex101.com/r/kfi8qI
Not sure how you are trying to put the strings together but
'.*' is greedily matching up to the last filename.
So, it should probably be '.*?'.
However, if the filenames are different then it shouldn't have matched.
Another thing is you should in general stop it from running past the next [alt] with
something like '[^\[\]]*'
Edit:
RegExp.escape('![') + '.*' + RegExp.escape(']') + RegExp.escape('(') + '.*' + RegExp.escape(fileName) + RegExp.escape(')'), 'i');
is the culprit.
Try
RegExp.escape('![') + '[^\]]*' + RegExp.escape(']') + RegExp.escape('(') + '[^\[\]]*?' + RegExp.escape(fileName) + RegExp.escape(')'), 'i');

Regex to get word started with # in javascript

I have a problem replace certain words started with #. I have the following code
var x="#google",
eval("var pattern = /" + '\\b' + x + '\\b');
txt.replace(pattern,"MyNewWord");
when I use the following code it works fine
var x="google",
eval("var pattern = /" + '\\b' + x + '\\b');
txt.replace(pattern,"MyNewWord");
it works fine
any suggestion how to make the first part of code working
ps. I use eval because x will be a user input.
The problem is that \b represents a boundary between a "word" character (letter, digit, or underscore) and a "non-word" character (anything else). # is a non-word character, so \b# means "a # that is preceded by a word character" — which is not at all what you want. If anything, you want something more like \B#; \B is a non-boundary, so \B# means "a # that is not preceded by a word character".
I'm guessing that you want your words to be separated by whitespace, instead of by a programming-language concept of what makes something a "word" character or a "non-word" character; for that, you could write:
var x = '#google'; // or 'google'
var pattern = new RegExp('(^|\\s)' + x);
var result = txt.replace(pattern, '$1' + 'MyNewWord');
Edited to add: If x is really supposed to be a literal string, not a regex at all, then you should "quote" all of the special characters in it, with a backslash. You can do that by writing this:
var x = '#google'; // or 'google' or '$google' or whatever
var quotedX = x.replace(/[^\w\s]/g, '\\$&');
var pattern = new RegExp('(^|\\s)' + quotedX);
var result = txt.replace(pattern, '$1' + 'MyNewWord');
Make you patter something like this:
/(#)?\w*/
If you want to make a Regular Expression, try this instead of eval:
var pattern = new RegExp(x);
Btw the line:
eval("var pattern = /" + '\\b' + x + '\\b');
will make an error because of no enclose pattern, should be :
eval("var pattern = /" + '\\b' + x + '\\b/');
How about
var x = "#google";
x.match(/^\#/);

JavaScript/Jquery Dynamic RegExp generation

I've searched this place a lot, and I'm stuck at that my regular expression works, but not dynamically.
id_name is the string that is picked dynamically. Then, the regexp should replace the match with a single var, which is in "vals". For some reason, when I code the regexp without the variable, it works as intended. I think I might do something wrong with the conversion to a regexp object.
Original String:
obj = values.replace(/{name}(.*?){\/name}/, 'igm');
Regexp Object:
re = '\/{' + id_name + '}(.*?){\\/' + id_name + '}\/';
regexp = new RegExp(re, 'igm');
obj = values.replace(regexp, vals);
Thanks in advance!
You don't need / and you also don't need to escape the character if you are constructing the regex via constructor:
re = '{' + id_name + '}(.*?){/' + id_name + '}';

Javascript regular expression is failing

I'm using the following javascript regex:
var pattern = new RegExp("^" + term + ".*")
console.log(pattern.toSource());
console.log(first_name + " : " + pattern.test(first_name) );
All i want it to do is check if the first name of the person begins with the search term given. E.g if the search term is 'a', then all the first names starting with a, e.g: andy, alice, etc should match. If its al, then only alice should match, etc. However the output is:
/^a.*/
Alyssa : false
What am I doing wrong?
Regexs are case-sensitive. So Alyssa won't match, because A and a are different symbols.
You may want to use case-insensitive regex match:
var pattern = new RegExp("^" + term + ".*", "i")
console.log(pattern.toSource());
console.log(first_name + " : " + pattern.test(first_name) );
There is nothing wrong, you should make the RegExp case insensitive using
var pattern = new RegExp("^" + term + ".*","i")
to match your name as long you want to render the test case insensitive or use a match like /^[aA].*/
You could specify your RegEx to be case insensitive, so that a will match both a and A:
var pattern = new RegExp("^" + term + ".*", "i");
Make your RegExp case insensitive:
var pattern = new RegExp("^" + term + ".*", "i");
See the documentation.
your regex is case sensitive so it's not matching Alyssa add this line to your code:
pattern.ignoreCase = true;
The reason it isn't working is that regular expressions are case sensitive. A is not a
Other things you are doing wrong:
Bothering to say "Followed by zero or more characters", that is just redundant.
Using a regular expression when a simple substring check will do the job.
I'd do it like this:
console.log(
first_name + " : " +
(first_name.toLowerCase().indexOf(term.toLowerCase()) === 0)
);

Categories