Use variable inside the regular expression in javascript [duplicate] - javascript

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 8 years ago.
My code:
var string = "I put putty on the computer. putty, PUT do I"
var uniques = {};
var result = (string.match(/\b\w*put\w*\b/ig) || []).filter(function(item) {
item = item.toLowerCase();
return uniques[item] ? false : (uniques[item] = true);
});
document.write( result.join(", ") );
Here i want pass a variable inside the expression
here i have pass a value 'put' and get answer. But i have to use variable for this value.
I have tried string.match(/\b\w*{+put+}\w*\b/ig
Can you share your answers

You should create a specific Regular Expression object to use with the .match() function. This way you can create your regex with a string and insert the variable when creating it:
var changing_value = "put";
var re = new RegExp("\\b\\w*" + changing_value + "\\w*\\b", "ig");
Note that the ignore case (i) and global (g) modifiers are specified as the second parameter to the RegExp constructor instead of part of the actual expression. Also that you need to escape the \ character inside the constructor because \ is also an escape character in strings.
Another thing to note is that you don't need the /delimiters/ at the start and end of the expression when using the Regexp constructor.
Now you can use the Regexp object in your call to .match():
string.match( re )
As a final note, I don't recommend that you use the name string as a variable name... As you can see from the syntax highlighting, string is a reserved word and it is not recommended to use names of built-in types for variable names as they may cause confusion.

Related

Transform a "Regex" string to actual Regex in Javascript [duplicate]

This question already has answers here:
Converting user input string to regular expression
(14 answers)
Closed 3 years ago.
I need to pass a regular expression in a validation function in my code that can only be set by an administrator in a back office platform as a string (e.g. '/^(?:\d{8}|\d{11})$/'). After it is passed I need to take this string and transform it into an actual javascript regex in order to use it.
const validator = (regex, value) => {
if (value && regex.test(value)) {
return 'Yeah!!';
}
return null;
};
So I need this '/^(?:\d{8}|\d{11})$/' to be like this /^(?:\d{8}|\d{11})$/.
You can initialize a regex with the RegExp method (documentation on MDN):
The RegExp constructor creates a regular expression object for matching text with a pattern.
const regex2 = new RegExp('^(?:\\d{8}|\\d{11})$');
console.log(regex2); // /^(?:\d{8}|\d{11})$/
You could instantiate the RegExp class and use it in two ways:
First:
new RegExp('<expression>').test(...)
Second:
/<expression>/.test(...)
Both ways will create an RegExp instance.
When to use one over the other?
Using the new RegExp way you can pass variables to the expression, like that:
new RegExp('^abc' + myVar + '123$');
Which you can't do using the second way.

Use match in replace [duplicate]

This question already has answers here:
Javascript string replace method. Using matches in replacement string
(2 answers)
Closed 3 years ago.
I need to put every non-alphabetic character between spaces.
I want to do this using RegExp, and I understand it enouch to select them all (/(^a-zA-Z )/g).
Is there a way to use the original match inside the replace?
(something like)
str.replace(/(^a-zA-Z )/g,/ \m /);
If not I will just loop over all of them, but I really want to know it it is possible.
Yes. You can give the String.prototype.replace() function a RegExp as it's search. You can also give it a function to handle replacing.
The function will give you the match as the first parameter, and you return what you want to change it to.
const original = 'a1b2c';
const replaced = original.replace(/([^a-z])/gi, match => ` ${match} `);
console.log(replaced);
If you just need to do something simple, you can also just use the $n values ($1, $2, etc) to replace based on the selected group (the sets of parentheses).
const original = 'a1b2c';
const replaced = original.replace(/([^a-z])/gi, ' $1 ');
console.log(replaced);
Yes, it is possible. You can use regex with group:
var text = '2apples!?%$';
var nextText = text.replace(/([^a-zA-Z])/g, ' $1 ');
console.log(nextText);
You can check replace function on this link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

How to use dynamic variable between regular expression [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 6 years ago.
I have string which contains some date and some comma separated values like this
var a = "1,13,20160308,200500000012016,10,Pending,01-02-2016,1|#|1,13,20160418,200500000012016,10,Pending,08-03-2016,1|#|1,13,20160623,200500000012016,10,Pending,18-04-2016,1|#|1,13,20160803,200500000012016,10,Pending,23-06-2016,1|#|1,13,20160912,200500000012016,10,Pending,03-08-2016,1|#|1,13,20161022,200500000012016,10,Pending,12-09-2016,1|#|1,13,20161129,200500000012016,10,Pending,22-10-2016,1|#|1,13,20170110,200500000012016,10,Pending,29-11-2016,1|#|1,13,20170215,200500000012016,10,Pending,10-01-2017,1|#|15-02-2017 APPEARANCE"
regular expression: /(.)*?01-02-2016(.)*?\|\#\|/igm
By using this regular expression i can able to delete unnecessary part in string.
Now i want to change 03-08-3016 (date) dynamically. If i use
var date = "01-02-2016"
var reg = /(.)*?${date}(.)*?\|\#\|/igm;
If you pring reg in console.log you will get like this below
console.log(reg) ----> output: '/(.)?01-02-2016(.)?|#|/igm'
Expected Final output will delete upto 01-02-2016,1|#|
Use this.
var regex="(.)*?01-02-2016(.)*?\\|\\#\\|";
var rx=new RegExp(regex,"igm");
console.log(rx);
//Then when do you want to change,
regex=regex.replace("01-02-2016","03-02-2016");
rx=new RegExp(regex,"igm");
console.log(rx);
JavaScript have 2 methods to make a Regular Expression.
1. write it in slashes //
2. Make from string using new RexExp(string);
If you make it from string, you can give the constraint(" global, incase, etc.") as the second parameter as i did in the above.
and also you have to double escape (\) the escape characters.

Global replace using variable [duplicate]

This question already has answers here:
Fastest method to replace all instances of a character in a string [duplicate]
(14 answers)
Closed 7 years ago.
In JavaScript I can uses a regex to replace tex:
var textSearch = "10";
var textReplace = "2";
var c = alayer.textItem.contents
c = c.replace(new RegExp(textSearch, "g"),textReplace);
alert(c);
text strings of "10" gets replaced with "2". Huzzah!
However, I was unable to do a global replace without a new RegExp constructor I got into a mess.
c = c.replace(textSearch, textReplace); //2 10 10
I tried various iterations of /g and "g" to no avail.
Do you have to uses regxEx in the form of new regExp() when using variables, or am I missing a trick? Reginald X. Pression where are you?? I need your help!
Indeed, normally you have to use a RegExp to replace more than once instance. There is however a non-standard third "flags" argument to replace() that should achieve a global replace even if you use a plain string as the search expression: c = c.replace('needle', haystack, 'g'); See the MDN reference. Note though that this extra argument is not supported in e.g. Chrome, so the RegExp approach is the best.

replace '\n' in javascript [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Fastest method to replace all instances of a character in a string [duplicate]
(14 answers)
Closed 1 year ago.
I'm trying to do replace in JavaScript using:
r = "I\nam\nhere";
s = r.replace("\n"," ");
But instead of giving me
I am here
as the value of s,
It returns the same.
Where's the problem??
As stated by the others the global flag is missing for your regular expression. The correct expression should be some thing like what the others gave you.
var r = "I\nam\nhere";
var s = r.replace(/\n/g,' ');
I would like to point out the difference from what was going on from the start.
you were using the following statements
var r = "I\nam\nhere";
var s = r.replace("\n"," ");
The statements are indeed correct and will replace one instance of the character \n. It uses a different algorithm. When giving a String to replace it will look for the first occurrence and simply replace it with the string given as second argument. When using regular expressions we are not just looking for the character to match we can write complicated matching syntax and if a match or several are found then it will be replaced. More on regular expressions for JavaScript can be found here w3schools.
For instance the method you made could be made more general to parse input from several different types of files. Due to differences in Operating system it is quite common to have files with \n or \r where a new line is required. To be able to handle both your code could be rewritten using some features of regular expressions.
var r = "I\ram\nhere";
var s = r.replace(/[\n\r]/g,' ');
use s = r.replace(/\\n/g," ");
Get a reference:
The "g" in the javascript replace code stands for "greedy" which means the replacement should happen more than once if possible
The problem is that you need to use the g flag to replace all matches, as, by default, replace() only acts on the first match it finds:
var r = "I\nam\nhere",
s = r.replace(/\n/g,' ');
To use the g flag, though, you'll have to use the regular expression approach.
Incidentally, when declaring variables please use var, otherwise the variables you create are all global, which can lead to problems later on.
.replace() needs the global match flag:
s = r.replace(/\n/g, " ");
It's working for me:
var s = r.split('\\n').join(' ');
replaceAll() is relative new, not supported in all browsers:
r = "I\nam\nhere";
s = r.replaceAll("\n"," ");
You can use:
var s = r.replace(/\n/g,' ').replace(/\r/g,' ');
because diferents SO use diferents ways to set a "new line", for example: Mac Unix Windows, after this, you can use other function to normalize white spaces.
Just use \\\n to replace it will work.
r.replace("\\\n"," ");
The solution from here worked perfect for me:
r.replace(/=(\r\n|\n|\r)/gm," ");

Categories

Resources