I would like to use .replace() function in JS to replace all occurencies of string "{5}".
I had no problems with letters in brackets but numbers just dont work if I call:
mystring.replace(/{\5}/g,'replaced')
nothing happens. Please can you help me with right syntax?
It looks like you have a problem with escaping. I'm pretty sure \5 is a backreference. You should instead be escaping the curly braces and not the number.
'Something {5} another thing'.replace(/\{5\}/g, 'replaced');
// -> Something replaced another thing
Additional Note: Just in case you're looking for a generalized string formatting solution, check out this SO question with some truly awesome answers.
Is there a special reason you are preceding the number with a backslash? If your intention is to match against the string "{5}", "{" and "}" are the special characters that should be escaped, not the character "5" itself!
According to MDN:
A backslash that precedes a non-special character indicates that the next character is
special and is not to be interpreted literally. For example, a 'b' without a preceding '\' generally matches lowercase 'b's wherever they occur. But a '\b' by itself doesn't match any character; it forms the special word boundary character.
The following code would work:
var str = "foo{5}bar{5}";
var newStr = str.replace(/\{5\}/g, "_test_");
console.log(newStr); // logs "foo_test_bar_test_"
Try this:
mystring.replace(/\{5\}/g,'replaced');
You need to escape the curly brackets\{ and \}.
DEMO
http://jsfiddle.net/tuga/Gnsq3/
Related
I have the below value as a plain text
`[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]sdsds\d\d`
I want to replace all [a-ZA-Z] with [C] and replace all \d with [N]. I tried to do this with the following code, but it does not work for \d.
value.replace(/\[a-zA-Z\]/g, '[C]').replace(/\\d/g, '[N]').replaceAll('\d', '[N]')
The final result must be:
[C][C][C][C]asass[N][N]
but it output
[C][C][C][C]s[N]s[N]s[N][N]
Note: I am getting this value from API and there is just one \ before d not \\.
The issue here might actually be in your source string. A literal \d in a JavaScript string requires two backslashes. Other than this, your replacement logic is fine.
var input = "[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]sdsds\\d\\d";
var output = input.replace(/\[a-zA-Z\]/g, '[C]').replace(/\\d/g, '[N]');
console.log(output);
You have some issues with \d. In the case of '\d' this will just result in 'd'. So maybe you wanted '\\d' as your starting string?
console.log('[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]sdsds\\d\\d'.replaceAll('[a-zA-Z]', '[C]').replaceAll('\\d', '[N]'));
When I use a tool like regexpal.com it let's me use regex as I am used to. So for example I want to check a text if there is a match for a word that is at least 3 letters long and ends with a white space so it will match 'now ', 'noww ' and so on.
On regexpal.com this regex works \w{3,}\s this matches both the words above.
But on javascript I have to add double backslashes before w and s. Like this:
var regexp = new RegExp('\\w{3,}\\s','i');
or else it does not work. I looked around for answers and searched for double backslash javascript regex but all I got was completely different topics about how to escape backslash and so on. Does someone have an explanation for this?
You could write the regex without double backslash but you need to put the regex inside forward slashshes as delimiter.
/^\w{3,}\s$/.test('foo ')
Anchors ^ (matches the start of the line boundary), $ (matches the end of a line) helps to do an exact string match. You don't need an i modifier since \w matches both upper and lower case letters.
Why? Because in a string, "\" quotes the following character so "\w" is seen as "w". It essentially says "treat the next character literally and don't interpret it".
To avoid that, the "\" must be quoted too, so "\\w" is seen by the regular expression parser as "\w".
I need a regex that will allow alphabets, hyphen (-), quote ('), dot (.), comma(,) and space. this is what i have now
^[A-Za-z\s\-]$
Thanks
I removed \s from your regex since you said space, and not white space. Feel free to put it back by replacing the space at the end with \s Otherwise pretty simple:
^[A-Za-z\-'., ]+$
It matches start of the string. Any character in the set 1 or more times, and end of the string. You don't have to escape . in a set, in case you were wondering.
You probably tried new RegExp("^[A-Za-z\s\-\.\'\"\,]$"). Yet, you have a string literal there, and the backslashes just escape the following characters - necessary only for the delimiting quote (and for backslashes).
"^[A-Za-z\s\-\.\'\"\,]$" === "^[A-Za-zs-.'\",]$" === '^[A-Za-zs-.\'",]$'
Yet, the range s-. is invalid. So you would need to escape the backslash to pass a string with a backslash in the RegExp constructor:
new RegExp("^[A-Za-z\\s\\-\\.\\'\\\"\\,]$")
Instead, regex literals are easier to read and write as you do not need to string-escape regex escape characters. Also, they are parsed only once during script "compilation" - nothing needs to be executed each time you the line is evaluated. The RegExp constructor only needs to be used if you want to build regexes dynamically. So use
/^[A-Za-z\s\-\.\'\"\,]$/
and it will work. Also, you don't need to escape any of these chars in a character class - so it's just
/^[A-Za-z\s\-.'",]$/
You are pretty close, try the following:
^[A-Za-z\s\-'.,]+$
Note that I assumed that you want to match strings that contain one or more of any of these characters, so I added + after the character class which mean "repeat the previous element one or more times".
Note that this will currently also allow tabs and line breaks in addition to spaces because \s will match any whitespace character. If you only want to allow spaces, change it to ^[A-Za-z \-'.,]+$ (just replaced \s with a space).
I'm trying this:
str = "bla [bla]";
str = str.replace(/\\[\\]/g,"");
console.log(str);
And the replace doesn't work, what am I doing wrong?
UPDATE: I'm trying to remove any square brackets in the string,
what's weird is that if I do
replace(/\[/g, '')
replace(/\]/g, '')
it works, but
replace(/\[\]/g, ''); doesn't.
It should be:
str = str.replace(/\[.*?\]/g,"");
You don't need double backslashes (\) because it's not a string but a regex statement, if you build the regex from a string you do need the double backslashes ;).
It was also literally interpreting the 1 (which wasn't matching). Using .* says any value between the square brackets.
The new RegExp string build version would be:
str=str.replace(new RegExp("\\[.*?\\]","g"),"");
UPDATE: To remove square brackets only:
str = str.replace(/\[(.*?)\]/g,"$1");
Your above code isn't working, because it's trying to match "[]" (sequentially without anything allowed between). We can get around this by non-greedy group-matching ((.*?)) what's between the square brackets, and using a backreference ($1) for the replacement.
UPDATE 2: To remove multiple square brackets
str = str.replace(/\[+(.*?)\]+/g,"$1");
// bla [bla] [[blaa]] -> bla bla blaa
// bla [bla] [[[blaa] -> bla bla blaa
Note this doesn't match open/close quantities, simply removes all sequential opens and closes. Also if the sequential brackets have separators (spaces etc) it won't match.
You have to escape the bracket, like \[ and \]. Check out http://regexpal.com/. It's pretty useful :)
To replace all brackets in a string, this should do the job:
str.replace(/\[|\]/g,'');
I hope this helps.
Hristo
Here's a trivial example but worked for me. You have to escape each sq bracket, then enclose those brackets within a bracket expression to capture all instances.
const stringWithBrackets = '[]]][[]]testing][[]][';
const stringWithReplacedBrackets = stringWithBrackets.replace(/[\[\]]/g, '');
console.log(stringWithReplacedBrackets);
Two backslashes produces a single backslash, so you're searching for "a backslash, followed by a character class consisting of a 1 or a right bracket, and then you're missing an closing bracket.
Try
str.replace(/\[1\]/g, '');
What exactly are you trying to match?
If you don't escape the brackets, they are considered character classes. This:
/[1\\]/
Matches either a 1 or a backslash. You may want to escape them with one backslash only:
/\[1\]/
But this won't match either, as you don't have a [1] in your string.
I stumbled on this question while dealing with square bracket escaping within a character class that was designed for use with password validation requiring the presence of special characters.
Note the double escaping:
var regex = new RegExp('[\\]]');
As #rudu mentions, this expression is within a string so it must be double escaped. Note that the quoting type (single/double) is not relevant here.
Here is an example of using square brackets in a character class that tests for all the special characters found on my keyboard:
var regex = new RegExp('[-,_,\',",;,:,!,#,#,$,%,^,&,*,(,),[,\\],\?,{,},|,+,=,<,>,~,`,\\\\,\,,\/,.]', 'g')
How about the following?
str = "bla [bla]";
str.replace(/[[\\]]/g,'');
You create a character set with just the two characters you are interested in and do a global replace.
Nobody quite made it simple and correct:
str.replace(/[[\]]/g, '');
Note the use of a character class, with no escape for the open bracket, and a single backslash escape for the close bracket.
I'd like to compare 2 strings with each other, but I got a little problem with the Brackets.
The String I want to seek looks like this:
CAPPL:LOCAL.L_hk[1].vorlauftemp_soll
Quoting those to bracket is seemingly useless.
I tried it with this code
var regex = new RegExp("CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll","gi");
var value = "CAPPL:LOCAL.L_hk[1].vorlauftemp_soll";
regex.test(value);
Somebody who can help me??
It is useless because you're using string. You need to escape the backslashes as well:
var regex = new RegExp("CAPPL:LOCAL.L_hk\\[1\\].vorlauftemp_soll","gi");
Or use a regex literal:
var regex = /CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll/gi
Unknown escape characters are ignored in JavaScript, so "\[" results in the same string as "[".
In value, you have (1) instead of [1]. So if you expect the regular expression to match and it doesn't, it because of that.
Another problem is that you're using "" in your expression. In order to write regular expression in JavaScript, use /.../g instead of "...".
You may also want to escape the dot in your expression. . means "any character that is not a line break". You, on the other hand, wants the dot to be matched literally: \..
You are generating a regular expression (in which [ is a special character that can be escaped with \) using a string (in which \ is a special character).
var regex = /CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll/gi;