I want to add a (variable) tag to values with regex, the pattern works fine with PHP but I have troubles implementing it into JavaScript.
The pattern is (value is the variable):
/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is
I escaped the backslashes:
var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "" + value + ""));
But this seem not to be right, I logged the pattern and its exactly what it should be.
Any ideas?
To create the regex from a string, you have to use JavaScript's RegExp object.
If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.
If you are trying to use a variable value in the expression, you must use the RegExp "constructor".
var regex = "(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")
I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:
str = "1x";
var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
inv=inv.replace(regex, "");
You don't need the " to define a regular expression so just:
var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
If value is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.
String.replace also accepts strings as input, so you can do "fox".replace("fox", "bear");
Alternative:
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Keep in mind that if value contains regular expressions characters like (, [ and ? you will need to escape them.
I found this thread useful - so I thought I would add the answer to my own problem.
I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.
This was my solution.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
After running, it will change the existing data directory setting to the new one:
config file before:
data_file_directories:
- /var/lib/cassandra/data
config file after:
data_file_directories:
- /mnt/cassandra/data
Much easier way: use template literals.
var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false
Using string variable(s) content as part of a more complex composed regex expression (es6|ts)
This example will replace all urls using my-domain.com to my-other-domain (both are variables).
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
note: Don't forget to use regex101.com to create, test and export REGEX code.
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps
I have a two strings like this
mystr = "xyz/10021abc/f123"
mystr2 = "abc/10021abd/c222"
I want to extract 10021abc and 10021abd. I came up with
r = regexp.MustCompile(`(?:xyz\/|abc\/)(.+)\/`)
But when I want to extract the match using this:
fmt.Println(r.FindString(mystr))
It returns the entire string. How should I change my regex?
You can use FindStringSubmatch.
var re = regexp.MustCompile(`(?:xyz\/|abc\/)(.+)\/`)
var s1 = "xyz/10021abc/f123"
var s2 = "abc/10021abd/c222"
fmt.Println(re.FindStringSubmatch(s1)[1])
fmt.Println(re.FindStringSubmatch(s2)[1])
https://go.dev/play/p/C93DbfzVv3a
You could use a regex replacement here:
var mystr = "xyz/10021abc/f123"
var re = regexp.MustCompile(`^.*?/|/.*$`)
var output = re.ReplaceAllString(mystr, "")
fmt.Println(output) // 10021abc
in flutter if we want to check if a string starts with a specific character...we can achieve that by:
var string = 'Dart';
string.startsWith('D'); // true
what if we want to check if the given string starts with multiple characters....i want to achieve this behaviour:
RegExp myRegExp = ('a-zA-Z0-9');
var string = 'Dart';
string.startsWith('D' + myRegExp);
is the above code is right?!!
my goal is to check if the string starts with a letter i specify...then a RegExp....
not to check if the string starts with 'D' only and thats it...
what if we want to check if the given string starts with multiple characters....i want to achieve this behaviour:
RegExp myRegExp = ('a-zA-Z0-9');
var string = 'Dart';
string.startsWith('D' + myRegExp);
That won't work. 'D' is a String object, and myRegExp presumably is intended to be a RegExp object. (Your syntax isn't correct; you probably want RegExp myRegExp = RegExp('[a-zA-Z0-9]');.) Both String and RegExp derive from a Pattern base class, but Pattern does not provide operator+, and String.operator+ works only with other Strings. Conceptually it's unclear what adding a String and RegExp should do; return a String? Return a RegExp?
You instead should just write a regular expression that accounts for your first character:
RegExp myRegExp = RegExp('D[a-zA-Z0-9]');
However, if you want the first character to be variable, then you can't bake it into the string literal used for the RegExp's pattern.
You instead could match the two parts separately:
var prefix = 'D';
var restRegExp = RegExp(r'[a-zA-Z0-9]');
var string = 'Dart';
var startsWith =
string.startsWith(prefix) &&
string.substring(prefix.length).startsWith(restRegExp);
Alternatively you could build the regular expression dynamically:
var prefix = 'D';
var restPattern = r'[a-zA-Z0-9]';
// Escape the prefix in case it contains any special regular expression
// characters. This is particularly important if the prefix comes from user
// input.
var myRegExp = RegExp(RegExp.escape(prefix) + restPattern);
var string = 'Dart';
var startsWith = string.startsWith(myRegExp);
I think you'll want something like string.startsWith(RegExp('D' + '[a-zA-Z0-9]'));
I have the following code (AS3 & CS 5.5):
var regEx:RegExp = new RegExp(/(?:^|\s)(\#[^\s$]+)/g);
var txt:String = "This #asd is a test tweet #hash1 test #hash2 test";
var matches:Object = regEx.exec(txt);
trace(matches);
The trace returns '#asd,#asd'. I really don't understand why it would to this, as in my RegEx testing application 'RegExhibit' it returns '#asd,#hash1,#hash2', which is what I'd expect. Can anyone shed any light on this please?
Thanks in advance!
If you are using .exec, you should run it multiple times to get all results:
In the following example, the g (global) flag is set in the regular expression, so you can use exec() repeatedly to find multiple matches:
var myPattern:RegExp = /(\w*)sh(\w*)/ig;
var str:String = "She sells seashells by the seashore";
var result:Object = myPattern.exec(str);
while (result != null) {
trace (result.index, "\t", result);
result = myPattern.exec(str);
}
Source: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/RegExp.html
A better alternative is probably to use String.match:
If pattern is a regular expression, in order to return an array with more than one matching substring, the g (global) flag must be set in the regular expression
An example should be (not tested):
var regEx:RegExp = /(?:^|\s)(\#[^\s$]+)/g;
var txt:String = "This #asd is a test tweet #hash1 test #hash2 test";
var matches:Object = txt.match(regEx);
I have a string that is similar to a path, but I have tried some regex patterns that are supposed to parse paths and they don't quite work.
Here's the string
f|MyApparel/Templates/Events/
I need the "name parts" between the slashes.
I tried (\w+) but the array came back [0] = "f" and [1] = "f".
I tested the pattern on http://www.gskinner.com/RegExr/ and it seems to work correctly.
Here's the AS code:
var pattern : RegExp = /(\w+)/g;
var hierarchy : Array = pattern.exec(params.category_id);
params.name = hierarchy.pop() as String;
pattern.exec() works like in JavaScript. It resets the lastIndex property every time it finds a match for a global regex, and next time you run it it starts from there.
So it does not return an array of all matches, but only the very next match in the string. Hence you must run it in a loop until it returns null:
var myPattern:RegExp = /(\w+)/g;
var str:String = "f|MyApparel/Templates/Events/";
var result:Object = myPattern.exec(str);
while (result != null) {
trace( result.index, "\t", result);
result = myPattern.exec(str);
}
I don't know between which two slashes you want but try
var hierarchy : Array = params.category_id.split(/[\/|]/);
[\/|] means a slash or a vertical bar.