The following code replaces only one single quote:
var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace("'", "\"");
console.log(b);
var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace(/'/g, '"');
console.log(b);
Edit: Removed \ as there are useless here.
Need to use regex for this:
var a = "[{'column1':'value0','column2':'value1','column3':'value2'}]";
var b = a.replace(/\'/g, "\"");
http://jsfiddle.net/9b3K3/
You can use a global qualifier (a trailing g) on a regular expression:
var b = a.replace(/'/g, '"');
Without the global qualifier, the regex (/'/) only matches the first instance of '.
replaceAll(search, replaceWith) replaces ALL occurrences of search with replaceWith.
Then, make sure you have a string by wrapping one type of qoutes by different type:
"a 'b' c".replaceAll("'", '"')
// result: "a "b" c"
"a 'b' c".replaceAll(`'`, `"`)
// result: "a "b" c"
More about replaceAll
replaceAll (MDN): replaceAll(search, replaceWith)
It's actually the same as using replace() with a global regex(*), merely replaceAll() is a bit more readable in my view.
(*) Meaning it'll match all occurrences.
Example 1 - search with a string
const p = 'Please replace all 2020 occurrences with 2021. 2020. 2020.'
console.log(p.replaceAll('2020', '2021'));
// Result: "Please replace all 2021 occurrences with 2021. 2021. 2021."
Example 2 - search with regex
const p = 'Please replace all 2020 occurrences with 2021. 2020. 2020.'
const regex = /2020/gi
console.log(p.replaceAll(regex, '2021'));
// Result: "Please replace all 2021 occurrences with 2021. 2021. 2021."
Important(!) if you choose regex:
when using a regexp you have to set the global ("g") flag;
otherwise, it will throw a TypeError: "replaceAll must be called with
a global RegExp".
You can also use a function as replaceWith
In this case, the function will be invoked after the match has been
performed. The function's result (return value) will be used as the
replacement string.
This looks suspiciously like bad JSON, so I suggest using actual array and object literals, then encoding the proper way:
var a = [{'column1':'value0','column2':'value1','column3':'value2'}];
var b = JSON.stringify(a);
Add the g modifier:
var b = a.replace(/'/g, '"');
You can use a RegExp with the global flag g and all quotes will replaced:
var b = a.replace(/'/g, '"');
Related
This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 2 years ago.
So for example:
function(input){
var testVar = input;
string = ...
string.replace(/ReGeX + testVar + ReGeX/, "replacement")
}
But this is of course not working :)
Is there any way to do this?
const regex = new RegExp(`ReGeX${testVar}ReGeX`);
...
string.replace(regex, "replacement");
Update
Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)
ES6 Update
In 2019, this would usually be written using a template string, and the above code has been updated. The original answer was:
var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");
You can use the RegExp object:
var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);
Then you can construct regexstring in any way you want.
You can read more about it here.
To build a regular expression from a variable in JavaScript, you'll need to use the RegExp constructor with a string parameter.
function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
of course, this is a very naive example. It assumes that input is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:
function regexEscape(str) {
return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
}
function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
input = regexEscape(input);
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
You can create regular expressions in JS in one of two ways:
Using regular expression literal - /ab{2}/g
Using the regular expression constructor - new RegExp("ab{2}", "g") .
Regular expression literals are constant, and can not be used with variables. This could be achieved using the constructor. The stracture of the RegEx constructor is
new RegExp(regularExpressionString, modifiersString)
You can embed variables as part of the regularExpressionString. For example,
var pattern="cd"
var repeats=3
new RegExp(`${pattern}{${repeats}}`, "g")
This will match any appearance of the pattern cdcdcd.
if you're using es6 template literals are an option...
string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")
You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.
You can also use RegExp constructor to pass flags in (see the docs).
It's only necessary to prepare the string variable first and then convert it to the RegEx.
for example:
You want to add minLength and MaxLength with the variable to RegEx:
function getRegEx() {
const minLength = "5"; // for exapmle: min is 5
const maxLength = "12"; // for exapmle: man is 12
var regEx = "^.{" + minLength + ","+ maxLength +"}$"; // first we make a String variable of our RegEx
regEx = new RegExp(regEx, "g"); // now we convert it to RegEx
return regEx; // In the end, we return the RegEx
}
now if you change value of MaxLength or MinLength, It will change in all RegExs.
Hope to be useful. Also sorry about my English.
Here's an pretty useless function that return values wrapped by specific characters. :)
jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/
function getValsWrappedIn(str,c1,c2){
var rg = new RegExp("(?<=\\"+c1+")(.*?)(?=\\"+c2+")","g");
return str.match(rg);
}
var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
var results = getValsWrappedIn(exampleStr,"(",")")
// Will return array ["5","19","thingy"]
console.log(results)
accepted answer doesn't work for me and doesn't follow MDN examples
see the 'Description' section in above link
I'd go with the following it's working for me:
let stringThatIsGoingToChange = 'findMe';
let flagsYouWant = 'gi' //simple string with flags
let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)
// that makes dynamicRegExp = /findMe/gi
I have the following code, which works, but I need to inject some different stuff into the regular expression object (regex2) at runtime. However, text.replace does not seem to like a string object for the regular expression, so how can I make this work?
var regex2 = /\|\d+:\d+/;
document.write("result = " + text.replace(regex2, '') + "<br>");
You can make a regular expression object from a string using the RegExp constructor function:
var regExp = new RegExp(myString); // regex pattern string
text.replace(regExp, '');
Addition to CMS:
The RegExp constructor has an second optional parameter flags
(15.10.4 The RegExp Constructor)
var text = "This is a Test.";
var myRegExp = new RegExp('teST','i');
text.replace(myRegExp,'Example');
// -> "This is a Example."
as Flags you can set
g -> global search (all occurrences)
i -> case insensitive
m -> multiline
var value = "2012-09-10";
value = value.replace(/([0-9]{4})[\/-]([0-9]{2})[\/-]([0-9]{2})/,"$3/$2/$1");
alert(value);
this will show
10/09/2012
you can use eval to,
new RegExp( eval("/"+str+"/i") );
bye...
I want to select all literal letter s but not literal word \s
(?<!\\)s
works in c# but I'm not able to adjust it to work with javascript. how do I disallow literal \s in javascript matching all literal s?
for example int the expression: test\ss should match test\ss
Edit:
as Mitch says I want to catch all literal s that are not after a literal \
You can create DIY Boundaries ...
var r = 'test\\ss'.replace(/(^|[^\\])s/gi, '$1ş');
console.log(r); //=> 'teşt\sş'
Or use a workaround:
var r = 'test\\ss'.replace(/(\\)?s/gi, function($0,$1) { return $1 ? $0 : 'ş'; });
According to your comment in your question, try this then
/(?:\B|\s)s/g
Try this in your browsers console to confirm it works
re = /(?:\B|\s)s/g;
str = 'test\\ss';
res = str.match(re)
console.log(str.replace(re, '0'));
res will have 2 results in it
I am getting this value from DatePicker
var datepickr = 'Jun-29-2011';
I want to replace underscores(-) with space .
I tried this way , but it isn't working
var b = datepickr.replace("-",' ');
Just for reference:
var datepickr = 'Jun-29-2011';
datepickr.replace("-", " "); // returns "Jun 29-2011"
datepickr.replace(/-/, " "); // returns "Jun 29-2011"
datepickr.replace(/-/g, " "); // returns "Jun 29 2011" (yay!)
The difference is the global modifier /g, which causes replace to search for all instances. Note also that - must be escaped as \- when it could also be used to denote a range. For example, /[a-z]/g would match all lower-case letters, whereas /[a\-z]/g would match all a's, z's and dashes. In this case it's unambiguous, but it's worth noting.
EDIT
Just so you know, you can do it in one line without regex, it's just impressively unreadable:
while (str !== (str = str.replace("-", " "))) { }
.replace is supposed to take a regular expression:
var b = datepickr.replace(/-/g,' ');
I'll leave it as an exercise to the reader to research regular expressions to the full.
(The important bit here, though, is the flag /g — global search)
Try this:
var datepickr = 'Jun-29-2011';
var b = datepickr.replace( /-/g, ' ' );
The /g causes it to replace every -, not just the first one.
var b = 'Jun-29-2011'.replace(/-/g, ' ');
Or:
var b = 'Jun-29-2011'.split('-').join(' ');
replace works with regular expressions, like so:
> "Hello-World-Hi".replace(/-/g, " ")
Hello World Hi
try:
var b = datepickr.toString().replace("-",' ');
I suspect that you are trying to replace chars inside a Date object.
This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 2 years ago.
So for example:
function(input){
var testVar = input;
string = ...
string.replace(/ReGeX + testVar + ReGeX/, "replacement")
}
But this is of course not working :)
Is there any way to do this?
const regex = new RegExp(`ReGeX${testVar}ReGeX`);
...
string.replace(regex, "replacement");
Update
Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)
ES6 Update
In 2019, this would usually be written using a template string, and the above code has been updated. The original answer was:
var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");
You can use the RegExp object:
var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);
Then you can construct regexstring in any way you want.
You can read more about it here.
To build a regular expression from a variable in JavaScript, you'll need to use the RegExp constructor with a string parameter.
function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
of course, this is a very naive example. It assumes that input is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:
function regexEscape(str) {
return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
}
function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
input = regexEscape(input);
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
You can create regular expressions in JS in one of two ways:
Using regular expression literal - /ab{2}/g
Using the regular expression constructor - new RegExp("ab{2}", "g") .
Regular expression literals are constant, and can not be used with variables. This could be achieved using the constructor. The stracture of the RegEx constructor is
new RegExp(regularExpressionString, modifiersString)
You can embed variables as part of the regularExpressionString. For example,
var pattern="cd"
var repeats=3
new RegExp(`${pattern}{${repeats}}`, "g")
This will match any appearance of the pattern cdcdcd.
if you're using es6 template literals are an option...
string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")
You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.
You can also use RegExp constructor to pass flags in (see the docs).
It's only necessary to prepare the string variable first and then convert it to the RegEx.
for example:
You want to add minLength and MaxLength with the variable to RegEx:
function getRegEx() {
const minLength = "5"; // for exapmle: min is 5
const maxLength = "12"; // for exapmle: man is 12
var regEx = "^.{" + minLength + ","+ maxLength +"}$"; // first we make a String variable of our RegEx
regEx = new RegExp(regEx, "g"); // now we convert it to RegEx
return regEx; // In the end, we return the RegEx
}
now if you change value of MaxLength or MinLength, It will change in all RegExs.
Hope to be useful. Also sorry about my English.
Here's an pretty useless function that return values wrapped by specific characters. :)
jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/
function getValsWrappedIn(str,c1,c2){
var rg = new RegExp("(?<=\\"+c1+")(.*?)(?=\\"+c2+")","g");
return str.match(rg);
}
var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
var results = getValsWrappedIn(exampleStr,"(",")")
// Will return array ["5","19","thingy"]
console.log(results)
accepted answer doesn't work for me and doesn't follow MDN examples
see the 'Description' section in above link
I'd go with the following it's working for me:
let stringThatIsGoingToChange = 'findMe';
let flagsYouWant = 'gi' //simple string with flags
let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)
// that makes dynamicRegExp = /findMe/gi