I am running up against a weird problem here. When I run:
"#/a/b/c/d".replace("#\/","")
I get what I would expect: a/b/c/d.
But When I precede this regex with a start of string character ^, To get:
"#/a/b/c/d".replace("^#\/","")
This returns the original string "#a/b/c/d".
Could anybody explain why the hash isn't removed and possibly suggest an alternative that would remove the hash only if it appears at the beginning of the string?
The first argument to replace can be either a string or a regular expression.
You are passing a string, so it is looking for an exact match for that string.
Pass a regular expression instead.
"#/a/b/c/d".replace(/^#\//,"")
When you pass a string as the first argument to .replace() method, the string is used as a literal and only 1 replacement can be made.
See the MDN replace reference:
substr (pattern)
A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression.
What you need is to pass the regex object as the first argument:
"#/a/b/c/d".replace(/^#\//,"")
^^^^^^
There is no point in using a constructor notation (RegExp("^#/") since the pattern is not built dynamically from variables.
There are no double slashes in the pattern! The outer /.../ are called regex delimiters. Then, what is insde is a pattern. The pattern is ^#/, but since the / are used as regex delimiters, the / in the pattern must be escaped to match a literal / (only in the regex literal notation).
String.replace takes as its first argument either a string or a regexp. If you give it a string, it is not interpreted as or converted to a regexp; it is treated literally. Therefore, when you add ^ to your string, it replaces nothing, since there is no ^ in the input.
As explained in the comments, you can either pass a regexp literal (/.../) as the first argument, or you could construct a regexp with new RegExp (but why would you do that?).
Related
I have the following in JavaScript:
function escape(text)
{
var tx = text.replace(/[&<>"']/g);
}
Im having problems trying to do the same on Dart:
var reg = new RegExp("/[&<>"']/g"); -->this throws error.
How can I get an equivalent expression?
The Dart RegExp source does not use / to delimit regular expressions, they're just strings passed to the RegExp constructor.
It's usually recommended that you use a "raw string" because backslashes mean something in RegExps as well as in non-raw string literals, and the JavaScript RegExp /\r\n/ would be RegExp("\\r\\n") in Dart without raw strings, but RegExp(r"\r\n") with a raw string, much more readable.
In this particular case, where the string contains both ' and ", that becomes harder, but you can use a "multiline string" instead - it uses tripple quote characters as delimiters, so it can contain single quote characters unescaped (it doesn't have to actually span multiple lines).
Dart doesn't have something similar to the g flag of JavaScript regexps. Dart regexps are stateless, it's the functions using them which need to care about remembering where it matched, not the RegExp itself. So, no need for the g.
So:
RegExp(r"""[&<>"']""");
// or
RegExp(r'''[&<>"']''');
That gets a little crowded with all those quotes, and you can choose to use a non-raw string instead so you can escape the quote which matches the string (which is easier because your RegExp does not contain any backslashes itself):
RegExp("[&<>\"']");
// or
RegExp('[&<>"\']');
If you do that when your regexp uses a RegExp backslash, then you'll need to double the backslash, something which is easy to forget, which is why raw strings are recommended.
You forgot to escape double quotes
new RegExp("/[&<>\"']", 'g');
I was converting normal string in to latex format.So i was created the latex code match and replace the \ single slash into \\ double slash.why the i need it Refer this link.I tried Below code :
function test(){
var tex="$$\left[ x=\left({{11}\over{2}}+{{\sqrt{3271}}\over{2\,3^{{{3}\over{2} $$";
var tex_form = tex.replace("/[\\\/\\\\\.\\\\]/g", "\\");
document.getElementById('demo').innerHTML=tex_form;//nothing get
}
test();
<p id="demo"></p>
Not getting any output data.But the match in this link
i wish to need replace the \ into \\
There are these issues:
The string literal has no backslashes;
The regular expression is not a regular expression;
The class in the intended regular expression cannot match sequences, only single characters;
The replacement would not add backslashes, only replace with them.
Here you find the details on each point:
1. How to Encode Backslashes in String Literals
Your tex variable has no backslashes. This is because a backslash in a string literal is not taken as a literal backslash, but as an escape for interpreting the character that follows it.
When you have "$$\left...", then the \l means "literal l", and so the content of your variable will be:
$$left...
As an l does not need to be escaped, the backslash is completely unnecessary, and these two assignments result in the same string value:
var tex="$$\left[ x=\left({{11}\over{2}}+{{\sqrt{3271}}\over{2\,3^{{{3}\over{2} $$";
var tex="$$left[ x=left({{11}over{2}}+{{sqrt{3271}}over{2,3^{{{3}over{2} $$";
To bring the point home, this will also represent the same value:
var tex="\$\$\l\e\f\t\[\ \x\=\l\e\f\t\(\{\{\1\1\}\o\v\e\r\{\2\}\}\+\{\{\s\q\r\t\{\3\2\7\1\}\}\o\v\e\r\{\2\,\3\^\{\{\{\3\}\o\v\e\r\{\2\}\ \$\$";
If you really want to have literal backslashes in your content (which I understand you do, as this is about LaTeX), then you need to escape each of those backslashes... with a backslash:
var tex="$$\\left[ x=\\left({{11}\\over{2}}+{{\\sqrt{3271}}\\over{2\\,3^{{{3}\\over{2} $$";
Now the content of your tex variable will be this string:
$$\left[ x=\left({{11}\over{2}}+{{\sqrt{3271}}\over{2\,3^{{{3}\over{2} $$
2. How to Code Regular Expression Literals
You are passing a string literal to the first argument of replace, while you really intend to pass a regular expression literal. You should leave out the quotes for that to happen. The / are the delimiters of a regular expression literal, not quotes:
/[\\\/\\\\\.\\\\]/g
This should not be wrapped in quotes. JavaScript understands the / delimiters as denoting a regular expression literal, including the optional modifiers at the end (like g here).
3. Classes are sets of single characters
This regular expression has unnecessary characters. The class [...] should list all individual characters you want to match. Currently you have these characters (after resolving the escapes):
\
/
\
\
.
\
\
It is overkill to have the backslash represented 5 times. Also, in JavaScript the forward slash and dot do not need to be escaped when occurring in a class. So the above regular expression is equivalent to this one:
/[\\/.]/g
Maybe this is, or is not, what you intended to match. To match several sequences of characters, you could use the | operator. This is just an example:
/\\\\|\\\/|\\\./g
... but I don't think you need this.
4. How to actually prefix with backslashes
It seems strange to me that you would want to replace a point or forward slash with a backslash. Probably you want to prefix those with a backslash. In that case make a capture group (with parentheses) and refer to it with $1 in this replace:
tex.replace(/([\\/.])/g, "\\$1");
Note again, that in the replacement string there is only one literal backslash, as the first one is an escape (see point 1 above).
why the i need it
As the question you link to says, the \ character has special meaning inside a JavaScript string literal. It represents an escape sequence.
Not getting any output data.But the match in this link
The escape sequence is processed when the string literal is parsed by the JavaScript compiler.
By the time you apply your regular expression to them, they have been consumed. The slash characters only exist in your source code, not in your data.
If you want to put a slash character in your string, then you need to write the escape sequence for it (the \\) in the source code. You can't add them back in with JavaScript afterwards.
Not sure if I understood the problem, but try this code:
var tex_form = tex.replace("/(\\)/g","\\\\");.
You need to use '(' ')' instead of '['']' to get a match for output.
I want to check if a string contains any of several symbols, including '$'. But the string.prototype.search() method returns last character index + 1 when searching for '$'
For example:
'abc'.search('$') //return 3
''.search('$') //return 0
I want to know why this is happening
From MDN:
regexp
Optional. A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
So your call is equivalent to:
'abc'.search(/$/);
$ in a regular expression matches the end of the string. If you want to disable the special meaning, you need to escape it:
'abc'.search('\\$')
You need two \ characters: the first escapes the backslash in the string literal, and this then escapes the dollar sign in the regexp. Or you could write:
'abc'.search(/\$/)
I have a JS function which is passed a string that a RegEx is run against, and returns any matches:
searchText= // some string which may or may not contain URLs
Rxp= new RegExp("([a-zA-Z\d]+://)?(\w+:\w+#)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(/.*)?/ig")
return searchText.match(Rxp);
The RegExp should return matches for any of the following (and similar derivations):
google.com
www.google.com
http://www.google.com
http://google.com
google.com?querystring=value
www.google.com?querystring=value
http://www.google.com?querystring=value
http://google.com?querystring=value
However, no such luck. Any suggestions?
In a string, \ has to be escaped: \\.
First, the string is interpreted. \w turns in w, because it has no significant meaning.
Then, the parsed string is turned in a RegEx. But \ is lost during the string parsing, so your RegEx breaks.
Instead of using the RegExp constructor, use RegEx literals:
Rxp = /([a-zA-Z\d]+:\/\/)?(\w+:\w+#)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(\/.*)?/ig;
// Note: I recommend to use a different variable name. Variables starting with a
// capital usually indicate a constructor, by convention.
If you're not 100% sure that the input is a string, it's better to use the exec method, which coerces the argument to a string:
return Rxp.exec(searchText);
Here's a pattern which includes the query string and URL fragment:
/([a-zA-Z\d]+:\/\/)?(\w+:\w+#)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(\/[^?#\s]*)?(\?[^#\s]*)?(#\S*)?/ig
Firstly, there's no real need to create your pattern via the RegExp constructor since it doesn't contain anything dynamic. You can just use the literal /pattern/ instead.
If you do use the constructor, though, you have to remember your pattern is declared as a string, not a literal REGEXP, so you'll need to double-escape special characters, e.g. \\d, not \d. Also, there were several forward slashes you weren't escaping at all.
With the constructor, modifiers (g, i) are passed as a second argument, not appended to the pattern.
So to literally change what you have, it would be:
Rxp= new RegExp("([a-zA-Z\\d]+:\\/\\/)?(\\w+:\\w+#)?([a-zA-Z\\d.-]+\\.[A-Za-z]{2,4})(:\\d+)?(\\/.*)?", "ig")
But better would be:
Rxp = /([a-zA-Z\d]+:\/\/)?(\w+:\w+#)?([a-zA-Z\d.-]+\.[A-Za-z]{2,4})(:\d+)?(\/.*)?/gi;
The following replacement
"index.html".replace('\.html$', '_fr.html');
returns "index.html", indicating that the first argument didn't match anything. However, if I remove the "$"
"index.html".replace('\.html', '_fr.html');
then the first argument matches and "index_fr.html" is returned.
Returning to the first example, can someone explain why ".html$" does not seem to match "index.html"?
Because that's not a regular expression - regex literals in JavaScript look like:
/\.html$/
without quotes. String.replace takes a string or a regular expression literal.