Javascript regex replace global object property with brackets [duplicate] - javascript

This question already has answers here:
Is there a RegExp.escape function in JavaScript?
(18 answers)
Closed 2 years ago.
I have a string, where I want to replace global myObj.value with myObj.name. I tried to construct a new RegExp object, but how to pass the square brackets ?
let param = {
name: '[year]',
value: '2019'
}
let str = 'Enter the number of days during [year] (they should not be more than your total days spent
during [year])'
I tried:
str.replace(new RegExp('param.name', 'g'), param.value);
and
str.replace(new RegExp(`\\[param.name\\]`, 'g'), param.value)

You can escape regex special characters in your 'name' parameter by using a custom function to do that. Below is a sample with a custom function to replace special regex characters obtained from How to escape regular expression special characters using javascript?.
let param = {
name: '[year]',
value: '2019'
}
let str = 'Enter the number of days during [year] (they should not be more than your total days spent during [year])'
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
alert(str);
str = str.replace(new RegExp(escapeRegExp(param.name), 'g'), param.value);
alert(str);

Related

Javascript check for a whole word in a unicode string [duplicate]

This question already has answers here:
Find words from array in string, whole words only (with hebrew characters)
(2 answers)
Match any non-word character (excluding diacritics)
(1 answer)
How to ban words with diacritics using a blacklist array and regex?
(5 answers)
Closed 3 years ago.
What is the correct way to check for a whole word in a unicode string in Javascript.
This works for ASCII only:
var strHasWord = function(word, str){
return str.match(new RegExp("\\b" + word + "\\b")) != null;
};
I tried XRegExp as follows but this does not work either.
var strHasWord = function(word, str){
// look for separators/punctuation characters or if the word is the first or the last in the string
var re = XRegExp("(\\p{Z}|\\p{P}|^)" + word + "(\\p{Z}|\\p{P}|$)");
return re.test(str);
//return str.match(re);
}
Any suggestions. Thanks.
EDIT 1
The following seems to do the trick.
var function strHasWord = function(word, str){
var re = RegExp("(\\p{Z}|\\p{P}|^)" + word + "(\\p{Z}|\\p{P}|$)", "u");
return str.match(re) != null;
//return re.test(str);
}

Regex replace with captured [duplicate]

This question already has answers here:
Using $0 to refer to entire match in Javascript's String.replace
(2 answers)
Closed 5 years ago.
I want replace all non alphanumeric character in the string by it self surrender for "[" and "]".
I tried this:
var text = "ab!#1b*. ef";
var regex = /\W/g;
var result = text.replace(regex, "[$0]");
console.log(result);
I was expecting to get:
ab[!][#]1b[*][.][ ]ef
But instead i get:
ab[$0][$0]1b[$0][$0][$0]ef
How can I do this using Javascript(node)?
You need to wrap the group in parentheses to assign it to $1, like this:
var text = "ab!#1b*. ef";
var regex = /(\W)/g;
var result = text.replace(regex, "[$1]");
console.log(result);

Javascript Regexp: Replace curly braces [duplicate]

This question already has answers here:
regular expression does not work with javascript
(2 answers)
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 7 years ago.
Folks,
I'm trying to replace a huge chunk of string with a multiple occurrences of "${country_id}". I need a Regular expression that can replace the ${country_id}. Here is the code I have:
var iterLiteral = "\$\{"+literal+"\}"
var re = new RegExp(iterLiteral,"g")
var value = value;
return body.replace(re,value)
I get this error:
Evaluator: org.mozilla.javascript.EcmaError: Invalid quantifier }
How can I fix it?
Edit:
String to be replaced: ${country_id}
literal being passed to the function : country_id.
Trying to use what Anubhava said ( using \\ ), the program tries to search for \$\{country_id\} and it doesn't find one.
Edit 2: Why is this a duplicate? the question that was mentioned doesn't talk about escaping.
If you have a set regular expression, you might find it easier to use the // syntax for defining the RegExp:
'foo: ${country_id}, bar: ${country_id}'.replace(/\$\{country_id\}/g, 'baz')
Alternatively, if the string must be constructed, then you need to double escape the slashes for them to be a part of the regular expression, and not seen as escaping characters for the creation of the string itself:
'foo: ${country_id}, bar: ${country_id}'.replace(new RegExp('\\$\\{' + 'country_id' + '\\}', 'g'), 'baz')
Your function would thus be:
function replaceLiteral(body, literal, value) {
var iterLiteral = "\\$\\{" + literal + "\\}";
var re = new RegExp(iterLiteral, "g");
return body.replace(re, value)
}
var result = replaceLiteral('foo: ${country_id}, bar: ${country_id}', 'country_id', 'baz');
console.log(result);
All of these output the same string:
'foo: baz, bar: baz'
Using double slashes ought to work, if your .replace function is correct (meaning that you use the regex as the first argument, not the iterLiteral). If it doesn't, there's something going wrong else where in your code. If that's the case, please provide the whole function you are using.
function fandr(literal, value, el) {
var iterLiteral = "\\$\\{" + literal + "\\}",
re = new RegExp(iterLiteral, "g"),
$el = $(el);
console.log(re);
$el.html(function() {
return $el.html().replace(re, value);
});
}
fandr("country_id", "banana", "span");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>${country_id}</span>

Get the same function for replace [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 8 years ago.
I have two strings like these
var temp = 'xx-y1 xx-y2 xx-y3';
var temp1 = 'zz-y1 zz-y2 zz-y3';
I wanna replace all the words started with "xx-" and "zz-" pattern and for this purpose I do this.
temp.replace(/\bxx-\S+/g, '');
temp.replace(/\bzz-\S+/g, '');
now my question is how can I have a single function and just call it?
I try to test this but it doesn't work!!!
func = function(str, pattern) {
return str.replace(RegExp('\b' + pattern + '\S+', 'g'), '');
}
You need to escape \ when calling RegExp constructor.
function replace(where, what) {
return where.replace(new RegExp('\\b' + what + '\\S+', 'g'), '');
}

Case insensitive in regex with Javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Case insensitive regex in javascript
Right now I have this:
my_list.match(new RegExp("(?:^|,)"+my_name+"(?:,|$)")))
Which, given the following:
my_list = "dog, cat, boy"
my_name = "dog"
Would return true.
However if I have
my_list = "Dog,Cat,boy"
and
my_name = "boy"
The regex wouldn't match. How would I adapt in order to be able to match with case insensitive?
First off: Never build a regular expression from an unescaped variable. Use this function to escape all special characters first:
RegExp.quote = function(str) {
return str.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
};
It modifies the RegExp object, you need to include it just once. Now:
function stringContains(str, token) {
var
spaces = /^\s+|\s+$/g, // matches leading/trailing space
token = token.replace(spaces, ""), // trim the token
re = new RegExp("(?:^|,)\\s*" + RegExp.quote(token) + "\\s*(?:,|$)", "i");
return re.test(str);
}
alert( stringContains("dog, cat, boy", " Dog ") );
Note
The "i" that makes the new RegExp case-insenstive.
The two added \s* that allow white-space before/after the comma.
The fact that "(?:^|,)\\s*" is correct, not "(?:^|,)\s*"" (in a JS string all backslashes need to be escaped).

Categories

Resources