How can I use a javascript regex backreference in a function? - javascript

var string = input.replace(/\[noparse\]([^\]]+)?\[\/noparse\]/ig, '<noparse>'+removeBrackets('$1')+'</noparse>');
This expression should be taking a string and encoding the parts wrapped in [noparse] tags so they don't render in a textarea.
I tested this as:
var string = input.replace(/\[noparse\]([^\]]+)?\[\/noparse\]/ig, '<noparse>test</noparse>');
and:
var string = input.replace(/\[noparse\]([^\]]+)?\[\/noparse\]/ig, '<noparse>'+String('$1')+'</noparse>');
and they work (without the desired effect).
function removeBrackets(input){
return input
.replace(/\[/g, '[')
.replace(/\]/g, '\');
}
What am I doing wrong in trying to pass the back reference into the removeBrackets function?

replace takes a function as callback and passes the capturing groups in the arguments:
var regex = /\[noparse\]([^\]]+)?\[\/noparse\]/ig;
string = string.replace(regex, function(_, match) {
return '<tag>'+ removeBrackets(match) +'</tag>';
});
The first param _ is the full string, unnecessary in most cases.

Your regular expression won't work, because of an error in the negative character set you're using. This fixes it:
input.replace(/\[noparse\]([^\[]+)?\[\/noparse\]/ig, '<noparse>test</noparse>');
^
Then, to perform the actual replacement, you need to pass a function as the second argument to .replace() instead of a simple string.

Related

simple javascript replace function [duplicate]

I have a string like aman/gupta and I want to replace it to aman$$gupta and for that I am using JavaScript replace method as follows:
let a = "aman/gupta"
a = a.replace("/", "$")
console.log(a) // 'aman$gupta'
a = "aman/gupta"
a = a.replace("/", "$$")
console.log(a) // 'aman$gupta'
a = "aman/gupta"
a = a.replace("/", "$$$")
console.log(a) // 'aman$$gupta'
Why are the 1st and 2nd case identical and I get the expected result when I use $$$ instead of $$?
It’s because $$ inserts a literal "$".
So, you need to use:
a = "aman/gupta";
a = a.replace("/", "$$$$"); // "aman$$gupta"
See the following special patterns:
Pattern
Inserts
$$
Inserts a "$".
$&
Inserts the matched substring.
$`
Inserts the portion of the string that precedes the matched substring.
$'
Inserts the portion of the string that follows the matched substring.
$n
Where n is a non-negative integer less than 100, inserts the _n_th parenthesized submatch string, provided the first argument was a RegExp object.
$<Name>
Where Name is a capturing group name. If the group is not in the match, or not in the regular expression, or if a string was passed as the first argument to replace instead of a regular expression, this resolves to a literal (e.g., "$<Name>").
Also you can use split and join for better performance and $ isn't special for those functions.
var a = "aman/gupta"
a = a.split('/').join('$$')
alert(a); // "aman$$gupta"
To avoid the need to escape special characters you can use anonymous function as a replacer
a = "aman/gupta";
a = a.replace("/", function() {return "$$"});
console.log(a); // "aman$$gupta"
String.prototype.replace() documentation
Specifying a function as a parameter
You can specify a function as the second parameter. 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. (Note: the above-mentioned special replacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.
The replace method provides replacement patterns that start with a dollar sign. One of them is $$ which inserts a single $. A single dollar sign in the replacement string will result in a literal one.
So if you want clean literal dollar signs, use $$ replacement patterns accordingly:
console.log('aman/gupta'.replace('/','$$')); // aman$gupta
console.log('aman/gupta'.replace('/','$$$$')); // aman$$gupta
console.log('aman/gupta'.replace('/','$$$$$$')); // aman$$$gupta
In regular expression replace with groups, if replacement is a variable, it needs to dollar sign escaped. Otherwise there will be bugs.
function escapeDollarSign(str) {
return str.replace(/\$/g, "$$$$")
}
Use below code its working for me.
var dollar = "$$$$";
console.log('abhishe/kadam'.replace('/', dollar.replace(new RegExp('\\$', 'g'), '$$$')));

Get replaced characters with javascript regex replace

I am currently replacing all non-letter characters using
var stringwithoutspecialCharacter = "testwordwithpunctiuation.".replace(/[^\w\s!?]/g, '');
The problem is that I do not know which special character will appear (that needs removing). However I do need to be able to access the removed special character after I've run some code with the word without the special character.
Example inputs:
"test".
(temporary)
foo,
Desired output:
['"','test','"',"."]
['(','temporary',')']
['foo',',']
How could this be achieved in javascript?
Edit: To get both valid and invalid characters, change the regular expression
Quick solution is to define an array to collect the matches.
Then pass in a function into your replace() call
var matches = [];
var matcher = function(match, offset, string) {
matches.push(match);
return '';
}
var stringwithoutspecialCharacter = "testwordwithpunctiuation.".replace(/[^\w\s!?]|[\w\s!?]+/g, matcher);
console.log("Matches: " + matches);

JavaScript: String.search() can't search "[]" or "()"

If you try searching strings such as "[]" or "()" using the search() function it doesn't work.
function myFunction() {
var str = "Visit []W3Schools!";
var n = str.search("[]");
document.getElementById("demo").innerHTML = n;
}
You can try on W3Schools at -
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_search
Searching [] returns -1, while searching () returns 0. Always.
Why is that?
String.search uses a RegExp, and converts its argument to one if it isn't already. [] and () are special characters to RegExp.
You can directly create a regexp and escape the characters like so:
var n = str.search(/\[\]/);
But if you're searching for a literal string, then you should be using String.indexOf instead.
var n = str.indexOf("[]");
The JavaScript search function takes a regular expression as its argument:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/search
In regular expressions, "[" and "(" are special characters.
Try replacing your function with this:
function myFunction() {
var str = "Visit []W3Schools!";
var n = str.search("\\[]");
document.getElementById("demo").innerHTML = n;
}
or better:
var n = str.search(/\[]/);
The '[' special character is escaped. Once that is escaped, the ']' does not need to be escaped because it is only treated special after an unescaped '['.
For more information about regular expressions in JavaScript, look here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
It's because search is expecting a regular expression. If a string is passed, then search will explicitly transform it into a regexp using new RegExp.
Calling it like str.search("[]") is like calling it str.search(/[]/) (nothing in the string matches an empty set so -1 is returned).
And calling it like str.search("()") is like calling it str.search(/()/) (the first empty string "" is found at the index 0).
I recommend looking for the docs on MDN not W3Schools.
Because the search string is a regular-expression and "[]" and "()" are both magic. You need to double-escape them:
str.search("\\[\\]")
Or even better, as ephemient points out:
str.indexOf("[]")

replace square bracket & curly brackets to round brackets in javascript or jquery

I have a string like this
var data = "{45}*[52]*{45}*[52]*{45}*[52]*69"
I need to replace all the square bracket & curly brackets to round brackets in javascript or jquery
I have tried this
.replace(/[\[\]']+/g,'')
but it replaces all the open and close brackets parallel
Expected result is = "(45)*(52)*(45)*(52)*(45)*(52)*69"
Any ideas ?
In a simple way you can use
"{45}*[52]*{45}*[52]*{45}*[52]*69".split(/[\{\[]/).join('(').split(/[\}\]]/).join(')')
You can call .replace() with a function as the second parameter.
With this function you can create a new substring which will be used as replacement.
str.replace(regexp|substr, newSubStr|function[, flags])
function (replacement)
A function to be invoked to create the new
substring (to put in place of the substring received from parameter
1). The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.
Specifying a function as a parameter
You can specify a function as the second parameter. 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. (Note: the above-mentioned special replacement patterns do not
apply in this case.) Note that the function will be invoked multiple
times for each full match to be replaced if the regular expression in
the first parameter is global.
"[abc]".replace(/\[|\]/g, function(m) {
var replacements = {"[": "(", "]": ")"}; return replacements[m];
});
in one replace
var data = "{45}*[52]*{45}*[52]*{45}*[52]*69";
data = data.replace(/[\[\{](\d+)[\]\}]/g, "($1)")
Though it will also replace [123} and {123] with (123) ... so not technically correct
if you want to only replace "correctly" formatted input, you need two replace calls
data = data.replace(/[\{](\d+)[\}]/g, "($1)").replace(/[\[](\d+)[\]]/g, "($1)")
I think
Try utilizing RegExp /(.\d{2}.)/ to match any character before two digits , two digits, any character ; .match() to match digits , return replacement string
var data = "{45}*[52]*{45}*[52]*{45}*[52]*69";
var res = data.replace(/(.\d{2}.)/g, function(match) {
return "(" + match.match(/\d+/)[0] + ")"
});
document.body.textContent = res;

JS - apostrophe - wont get replaced

I'm having this problem with the apostrophe ("'") in JS. I'm using the encodeURIComponent() to encode this and then replace the (') with (%27) as follows.
var request = encodeURIComponent(requestString).replace("'", "%27");
But if the apostrophe is with a bracket, the apostrophe wont get replaced.
ex: (")'")
("')")
("('")
Even when the apostrophe is followed by a numeric number it wont get replaced.
Is there a solution for this?
Thanks in advance.
Nilushi
String.replace method accepts a string or regular expression as its first parameter. When a string is passed as the first parameter, only the first match is replaced:
"'''''".replace("'", "%27"); // "%27''''"
You should use a regular expression instead along with the g flag; which replaces ALL matches:
"'''''".replace(/'/g, "%27"); // "%27%27%27%27%27"
You need to specify /g global modifier:
var request = encodeURIComponent(requestString).replace(/'/g, "%27");
Example:
var str = "(''')";
var request = encodeURIComponent(str).replace(/'/g, "%27");
console.log(request); // (%27%27%27)

Categories