Javascript : replace reg exp - javascript

I want to replace all symbols that aren't letters by -, but my code doesn't work :
$reg = '/[^a-zA-Z]+/g';
$txt = $txt.replace($reg, '-');
What am I doing wrong?

Regular Expressions in JavaScript are not strings.
reg = /[^a-z]+/gi;
txt = txt.replace(reg, '-');
You don't need to place quotes around them.

You need to un-quote the regex string so it's treated as a regular expression literal, so you get this:
$reg = /[^a-zA-Z]+/g;
$txt = $txt.replace($reg, '-');
Regular expressions in JavaScript don't need to be quoted as strings unless using the new Regexp() notation; in the above example, it is now a regular expression literal, which isn't treated as a string but a piece of regex to be used in .replace().

do not use quote on regex. Without quotes, they are RegEx object. With quotes they are just string.
Use,
$reg = /[^a-zA-Z]+/g;

Remove the quotes from around your regex.
If it is your intention for multiple non-alpha characters in a row to be replaced with a single hyphen your regex will then work. If you want multiple non-alpha characters to be replaced with multiple hyphens then you should also remove the + sign.

Related

why does this js RegExp test return true? [duplicate]

The regex allows chars that are: alphanumeric, space, '-', '_', '&', '()' and '/'
this is the expression
[\s\/\)\(\w&-]
I have tested this in various online testers and know it works, I just can't get it to work correctly in code. I get sysntax errors with anything I try.. any suggestions?
var programProductRegex = new RegExp([\s\/\)\(\w&-]);
You can use the regular expression syntax:
var programProductRegex = /[\s\/\)\(\w&-]/;
You use forward slashes to delimit the regex pattern.
If you use the RegExp object constructor you need to pass in a string. Because backslashes are special escape characters inside JavaScript strings and they're also escape characters in regular expressions, you need to use two backslashes to do a regex escape inside a string. The equivalent code using a string would then be:
var programProductRegex = new RegExp("[\\s\\/\\)\\(\\w&-]");
All the backslashes that were in the original regular expression need to be escaped in the string to be correctly interpreted as backslashes.
Of course the first option is better. The constructor is helpful when you obtain a string from somewhere and want to make a regular expression out of it.
var programProductRegex = new RegExp(userInput);
If you are using a String and want to escape characters like (, you need to write \\( (meaning writing backslash, then the opening parenthesis => escaping it).
If you are using the RegExp object, you only need one backslash for each character (like \()
Enclose your regex with delimiters:
var programProductRegex = /[\s\/)(\w&-]/;

Regex for both newline and backslash for Replace function

I am using a replace function to escape some characters (both newline and backslash) from a string.
Here is my code:
var str = strElement.replace(/\\/\n/g, "");
I am trying to use regex, so that I can add more special characters if needed. Is this a valid regex or can someone tell me what am I doing wrong here?
You're ending the regex early with an unescaped forward slash. You also want to use a set to match individual characters. Additionally you might want to add "\r" (carriage return) in as well as "\n" (new line).
This should work:
var str = strElement.replace(/[\\\n\r]/g, "");
This is not a valid regex as the slash is a delimiter and ends the regex. What you probably wanted is the pipe (|), which is an alternation:
var str = strElement.replace(/\\|\n/g, "");
In case you need to extend it in the future it may be helpful to use a character class to improve readability:
var str = strElement.replace(/[\\\nabcx]/g, "");
A character class matches a single character from it's body.
This should work. The regular expression replaces both the newline characters and the backslashes in escaped html text:
var str = strElement.replace(/\\n|\\r|\\/g, '');

build Regex string with js

<script>
var String = "1 Apple and 13 Oranges";
var regex = /[^\d]/g;
var regObj = new RegExp(regex);
document.write(String.replace(regObj,''));
</script>
And it works fine - return all the digits in the string.
However when I put quote marks around the regex like this:
var regex = "/[^\d]/g"; This doesn't work.
How can I turn a string to a working regex in this case?
Thanks
You can create regular expressions in two ways, using the regular expression literal notation, or RegExp constructor. It seems you have mixed up the two. :)
Here is the literal way:
var regex = /[^\d]/g;
In this case you don't have use quotes. / characters at the ends serve as the delimiters, and you specify the flags at the end.
Here is how to use the RegExp constructor, in which you pass the pattern and flags (optional) as string. When you use strings you have to escape any special characters inside it using a '\'.
Since the '\' (backslash) is a special character, you have to escape the backslash using another backslash if you use double quotes.
var regex = new RegExp("[^\\d]", "g");
Hope this makes sense.
As slash(\) has special meaning for strings (e.g. "\n","\t", etc...), you need to escape that simbol, when you are passing to regexp:
var regex = "[^\\d]";
Also expression flags (e.g. g,i,etc...) must be passed as separate parameter for RegExp.
So overall:
var regex = "[^\\d]";
var flags = "g";
var regObj = new RegExp(regex, flags);

Brackets in Regular Expression

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;

javascript: some problem with compiler interpreting // as comments in regex

I've got this regular expression for validating phone numbers
^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.//-]|\([ 0-9.//-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\([ 0-9.//-]+\)))?$
I dugged it out from my C#/vb library and now i want to translate it into javascript. But it has syntax error (i suspect it is something due to the // characters). my attempt:
$IsPhone = function (input) {
var regex = new window.RegExp("^$|^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.//-]|\([ 0-9.//-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.//-]|\([ 0-9.//-]+\)))?$", "");
return regex.test(input.trim());
};
alert($IsPhone("asd"));
Your problem has nothing to do with comments. You're just mixing up the two different ways of creating RegExp objects.
When you create a RegExp object in JavaScript code, you either write it as a string literal which you pass to a RegExp constructor, or as a regex literal. Because string literals support backslash-escape sequences like \n and \", any actual backslash in the string has to be escaped, too. So, whenever you need to escape a regex metacharacter like ( or +, you have to use two backslashes, like so:
var r0 = "^$|^(\\+?|(\\(\\+?[0-9]{1,3}\\))|)([ 0-9./-]|\\([ 0-9./-]+\\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9./-]|\\([ 0-9./-]+\\)))?$";
var regex0 = new RegExp(r0, "");
The forward-slash has no special meaning, either to regexes or strings. The only reason you ever have to escape forward-slashes is because they're used as the delimiter for regex literals. You use backslashes to escape the forward-slashes just like you do with regex metacharacters like \( or \+, or the backslash itself: \\. Here's the regex-literal version of your regex:
var regex1 = /^$|^(\+?|(\(\+?[0-9]{1,3}\))|)([ 0-9.\/-]|\([ 0-9.\/-]+\))+((x|X|((e|E)(x|X)(t|T)))([ 0-9.\/-]|\([ 0-9.\/-]+\)))?$/;
from Errors translating regex from .NET to javascript
The backslash character in JavaScript
strings is an escape character, so the
backslashes you have in your string
are escaping the next character for
the string, not for the regular
expression. So right near the
beginning, in your "^(+?, the
backslash there just escapes the + for
the string (which it doesn't need),
and what the regexp sees is just a raw
+ with nothing to repeat. Hence the error.

Categories

Resources