Regex javascript, why dot and comma are matching for \ - javascript

Why this regex '^[0-9]+\.?[0-9]*$' match for 12.2 and 12,2 ?
jsFiddle
var dot = '12.2',
comma = '12,2',
regex = '^[0-9]+\.?[0-9]*$';
alert( dot.match(regex) );
alert( comma.match(regex) );
While it works on regexpal.com

Because the variable regex is a string the escape sequence \. is just ., which matches any character (except newline). If you change the definition of regex to use RegExp literal syntax or escape the escape character (\\.) then it will work as you expect.
var dot = '12.2'
, comma = '12,2'
, regex = /^[0-9]+\.?[0-9]*$/;
// or '^[0-9]+\\.?[0-9]*$'
alert(dot.match(regex));
alert(comma.match(regex));

Are you sure you don't need to escape the back-slash? It is in a string, you know...
regex = /^[0-9]+\.?[0-9]*$/
or
regex = "^[0-9]+\\.?[0-9]*$"
Actually, I'd recommend that you write it this way:
regex = /^\d+(\.\d+)?$/

Since you write your regex in a string, you need to escape the slash.
regex = '^[0-9]+\\.?[0-9]*$';

Your regex should be
regex = /^[0-9]+\.?[0-9]*$/;
Consult https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp for proper syntax.

Related

Replace all "+" with "%20" using Javascript

In the following text:
"123+456+789"
How can I replace all the "+" characters with %20?
The examples I have seen that use regular expressions end up treating the + as part of the rules used by the expression, so it seems regular expressions cannot be used.
You just need to escape the + first, which is done with a backslash:
const str = "123+456+789";
console.log(
str.replace(/\+/g, '%20')
);
The same thing is true for any character with a special meaning in a regular expression, like parentheses, *, ^, and so on - to match a literal character, put a backslash in front of it. (Same for the backslash itself - \\ matches a literal backslash)
You can use String#split() and Array#join() to remove all plusses and replace them with %20:
let plus = "123+456+789";
let percent = plus.split("+").join("%20");
console.log(percent)
You can achieve this by using str replace
str = document.getElementById("mystring").innerHTML;
res = str.replace("+", "%20");

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, '');

RegEx .replace() is not working

RegEx = new RegExp(sourcevalue, "gi");
temp[i] = Selectors[i].cssText.replace(RegEx, targetvalue);
where sourcevalue = rgb(255,0,0) and targetvalue = #FFFFFF, but sourcevalue is not replaced by targetvalue, why?
Most likely because you did not escape the parenthesis properly:
var sourcevalue = "rgb\\(255,0,0\\)";
Parenthesis are used for grouping/back-referencing matches. If you want to match them literally, you have to escape them with \. Since sourcevalue is a string and \ is the escape character in a string as well, you have to escape the backslash to create a literal one.
Otherwise, the expression would match rgb255,0,0 but not rgb(255,0,0).
Because sourcevalue is a correct Javascript regular expression but it's not working the way you expected. There are special characters in regular expression like the () parentheses. They are used to group parts of regular expressions. To use them with their "literal" meaing you'll have to escape them using backslashes
var RegEx = /rgb\(255,0,0\)/gi;

Javascript : replace reg exp

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.

Finding Plus Sign in Regular Expression

var string = 'abcd+1';
var pattern = 'd+1'
var reg = new RegExp(pattern,'');
alert(string.search(reg));
I found out last night that if you try and find a plus sign in a string of text with a Javascript regular expression, it fails. It will not find that pattern, even though it exists in that string. This has to be because of a special character. What's the best way to find a plus sign in a piece of text? Also, what other characters will this fail on?
Plus is a special character in regular expressions, so to express the character as data you must escape it by prefixing it with \.
var reg = /d\+1/;
\-\.\/\[\]\\ **always** need escaping
\*\+\?\)\{\}\| need escaping when **not** in a character class- [a-z*+{}()?]
But if you are unsure, it does no harm to include the escape before a non-word character you are trying to match.
A digit or letter is a word character, escaping a digit refers to a previous match, escaping a letter can match an unprintable character, like a newline (\n), tab (\t) or word boundary (\b), or a a set of characters, like any word-character (\w), any non-word character (\W).
Don't escape a letter or digit unless you mean it.
Just a note,
\ should be \\ in RegExp pattern string, RegExp("d\+1") will not work and Regexp(/d\+1/) will get error.
var string = 'abcd+1';
var pattern = 'd\\+1'
var reg = new RegExp(pattern,'');
alert(string.search(reg));
//3
You should use the escape character \ in front of the + in your pattern. eg. \+
You probably need to escape the plus sign:
var pattern = /d\+1/
The plus sign is used in regular expressions to indicate 1 or more characters in a row.
It should be var pattern = '/d\\+1/'.
The string will escape '\\' as '\' ('\\+' --> '\+') so the regex object init with /d\+1/
if you want to use + (plus sign) or $ (sigil /dollar sign), then use \ (backslash) as a prefix. Like that:
\$ or \+

Categories

Resources