I am trying to use javascript's replace function to replace a string. But it just replaces the first instance. So when I use regular global expressions,
var result = 'moaning|yes you|hello test|mission control|com on'.replace(/|/g, ';');
I get: http://jsfiddle.net/m8UuD/196/
I want to get:
moaning;yes you;hello test;mission control;com on
Simply escape the pipe :
'moaning|yes you|hello test|mission control|com on'.replace(/\|/g, ';');
Here you'll find the list of regex special characters that you should generally escape.
var result = 'moaning|yes you|hello test|mission control|com on'.replace(/\|/g, ';');
You could also use .split() and .join():
'moaning|yes you|hello test|mission control|com on'.split('|').join(';')
You need to escape the '|' like:
var result = 'moaning|yes you|hello test|mission control|com on'.replace(/\|/g, ';');
http://jsfiddle.net/PM4PT/
Many characters are reserved because have a special meaning in a regular expression, so to use one of them you need to "escape" it by placing a backslash \ right before the special character. These are:
( start of a sub-expression
) end of a sub-expression
{ start of repetition range
} end of a repetition range
[ start of a character set
] end of a character set
+ one or more repetitions
* zero or more repetitions
^ start of string
$ end of string
| "or" connection between alternatives
\ start of special code or escape
/ start or end of regexp pattern
For example a regular exprerssion to match all open square bracket is /\[/ (note the backslash). If you need to look for a backslash you must but a backslash in front of it (so doubling it).
Unfortunately there is no predefined Javascript function for "escaping" all special characters.
Related
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");
Example string: George's - super duper (Computer)
Wanted new string: georges-super-duper-computer
Current regex: .replace(/\s+|'|()/g, '-')
It does not work and and when I remove the spaces and there is already a - in between I get something like george's---super.
tl;dr Your regex is malformed. Also you can't conditionally remove ' and \s ( ) in a single expression.
Your regex is malformed since ( and ) have special meanings. They are used to form groups so you have to escape them as \( and \). You'll also have to place another pipe | in between them, otherwise you're going to match the literal "()", which is not what you want.
The proper expression would look like this: .replace(/\s+|'|\(|\)/g, '-').
However, this is not what you want. Since this would produce George-s---super-duper--Computer-. I would recommend that you use Character Classes, which will also make your expression easier to read:
.replace(/[\s'()-]+/g, '-')
This matches whitespace, ', (, ) and any additional - on or more times and replaces them with -, yielding George-s-super-duper-Computer-.
This is still not quite right, so have this:
var myString = "George's - super duper (Computer)";
var myOtherString = myString
// Remove non-whitespace, non-alphanumeric characters from the string (note: ^ inverses the character class)
// also trim any whitespace from the beginning and end of the string (so we don't end up with hyphens at the start and end of the string)
.replace(/^\s+|[^\s\w]+|\s+$/g, "")
// Replace the remaining whitespace with hyphens
.replace(/\s+/g, "-")
// Finally make all characters lower case
.toLowerCase();
console.log(myString, '=>', myOtherString);
You could do match instead of replace then join result on -. Then you may need a replace to remove single quotes. Regex would be:
[a-z]+('[a-z]+)*
JS code:
var str = "George's - super duper (Computer)";
console.log(
str.match(/[a-z]+('[a-z]+)*/gi).join('-').replace("'", "").toLowerCase()
);
I defined a function in JavaScript that replace all -, _, #, #, $ and \ (they are possible separators) with / (valid separator).
My goal is any string like "1394_ib_01#13568" convert to "1394/ib/01/13568"
function replaceCharacters(input) {
pattern_string = "-|_|#|#|$|\u005C"; // using character Unicode
//pattern_string = "-|_|#|#|$|\"; // using original character
//pattern_string = "-|_|#|#|$|\\"; // using "\\"
//pattern_string = "\|-|_|#|#|$"; // reposition in middle or start of string
pattern = new RegExp(pattern_string, "gi");
input = input.replace(pattern, "/");
return input;
}
My problem is when a string with \ character send to function result is not valid.
I tried use Unicode of \ in define pattern, Or use \\\ instead of it. Also I replaced position of it in pattern string. But in any of this situation, problem wasn't solved and browser return invalid result or different error such as:
SyntaxError: unterminated parenthetical ---> in using "\u005C"
SyntaxError: \ at end of pattern ---> in using "\\"
Invalid Result: broken result in 2 Line or replace with undefined character based on input string (the character after "\" determine result)
---> in reposition it in middle or start of pattern string
var pattern_string = "-|_|#|#|\\$|\\\\";
You have to escape the slash once for the pattern, so it'll try to match the literal character:
\\
Then, escape each slash again for the string literal:
"\\\\"
Also note that I added an escape for the $. To match a dollar sign literally, it'll needs to be escaped as well, since it normally represents an anchor for the "end of the line/string."
You can also use a Regex literal to avoid the string, using only the escape sequences necessary for the pattern:
var pattern = /-|_|#|#|\$|\\/gi;
And, as you're matching only single characters, you can use a character class instead of alternation:
var pattern = /[-_##\$\\]/gi;
(Just be careful with the placement of the - here. It's fine as the first character in the class, but can represent a range of characters when placed in the middle. You can also escape it to ensure it doesn't represent a range.)
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.
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 \+