I have the following function:
function replace(path) {
return path.replace(/\//g, '.').replace(/^\./, '');
};
Can you please explain what exactly is doing? I have some hard time understanding it mostly because of the slashes and escapes.
I know it replaces something with something. :)
return path.replace(/\//g, '.').replace(/^\./, '');
The / at the start and end are delimiters of regex.
The \ inside it will escape the following character(\ and .).
/\//g: Will find all(g: global flag) the / in the string and will replace it by .
/^\./: Will find the . at the start(^) of the string and will remove it
Replace / with ., and then replace . at the beginning of string with an empty string.
Let's assume that path is a string. strings in javascript, like everything else, are objects. Among other things, they have a replace function. You can read about it here.
Those things with the slashes are called regular expressions, or RegExs for short. You can read about them here and here. They are very useful and often used for manipulating strings with operations like replace.
Related
I know this question had been asked lot of time but i could not find solution. I have some smilies which each of them has code to be rendered as smiley using replace() , but I get syntax error, I don't know why and how to render my code :/ to smiley
txt = " Hi :/ ";
txt.replace("/\:/\/g","<img src='img/smiley.gif'>");
Your regular expression doesn't need to be in quotes. You should escape the correct / forward slash (you were escaping the wrong slash) and assign the replacement, since .replace doesn't modify the original string.
txt = " Hi :/ ";
txt = txt.replace(/:\//g,"<img src='img/smiley.gif'>");
Based on jonatjano's brilliant deduction, I think you should add a little more to the regular expression to avoid such calamities as interfering with URLs.
txt = txt.replace(/:\/(?!/)/g,"<img src='img/smiley.gif'>");
The above ensures that :// is not matched by doing a negative-lookahead.
There are two problems in the first argument of replace() it escapes the wrong characters and it uses a string that seems to contain a regex instead of a real RegExp.
The second line should read:
txt.replace(/:\//g,"<img src='img/smiley.gif'>");
/:\//g is the regex. The first and the last / are the RegExp delimiters, g is the "global" RegExp option (String.replace() needs a RegExp instead of a string to do a global replace).
The content of the regex is :/ (the string you want to find) but because / has a special meaning in a RegExp (see above), it needs to be escaped and it becomes :\/.
I have the following Javascript code to obtain the inner string from an RegExp:
Function.prototype.method = function (name,func){
this.prototype[name] = func;
return this;
};
RegExp.method('toRawString', function(){
return this.toString().replace(/^.(.*).$/,"$1");
});
The purpose of this, is to avoid in string double quoting. For example, if you have a Windows file path "C:\My Documents\My Folder\MyFile.file", you can use it like the following:
alert(/C:\My Documents\My Folder\MyFile.file/.toRawString());
However it is not working for ""C:\My Documents\My Folder\" since it causes syntax error. The only way to avoid it is to keep double quoting at the end of the string. Thus it will be written
alert(/C:\My Documents\My Folder\\/.toRawString());
The fact is any odd number of back slashes on the end of the string will be an error, so all ending back slashes must be double escaped. It will not be hard to use a multiple line small implementation, but are there any single RegExp solution?
NOTE
When using toRawString the RegExp object for this is usually NOT going to be used for any other purpose except for that method. I just want to use the syntax of RegExp to avoid double back slashes in source code. Unfortunately the ending double slashes cannot be easily avoid. I think another workaround is to force a space at the end but that is another question then.
UPDATE
I finally solved the "another question" and posted the code here.
OK, I get what you're trying to do! It's hacky : )
Try something like:
return this.toString().slice(1, -1).replace(/\\+$/, '\\')
Hope that helps.
If you want to include the double quotes in the string just wrap it with single quotes.
s = '"C:\\My Documents\\My Folder\\MyFile.file"'
console.log(s) // Output => "C:\My Documents\My Folder\MyFile.file"
This produces a syntax error:
/C:\My Documents\/
But that regular expression could be written correctly like this:
/C:\\My Documents\\/
Or like this:
new RegExp("C:\\\\My Documents\\\\")
I think your function is just fine and is returning a correct result. Regular expressions just can't end with an unpaired backslash. It's not that you're double escaping - you're just escaping the escape character.
This would produce an error too:
new RegExp("C:\\My Documents\\")
A regular expression like this, for instance, can't be written without a pair of backslashes:
/C:\\What/
Without the second backslash, \W would be interpreted as a special character escape sequence. So escaping the escape character isn't only necessary at the end. It's required anywhere it might be interpreted as the beginning of an escape sequences. For that reason, it might be a good rule of thumb to always use two backslashes to indicate a backslash literal in a regular expression.
I am trying to find a way to check if a string contains a specific sequence of characters in JScript.
In my case, I am trying to see if the string is "DPObject" followed by a number. Such as "DPObject3" or "DPObject14".
Thank you!
if (/DPObject\d+/.test(string)) {....}
Javascript String has an indexOf method you can use to check if a String contains a particular substring .
If you need to test for patterns , like "DPObject" followed by an integer , probably you need to use Regexes . ( http://www.regular-expressions.info )
It's javascript , or js for short - not JScript .
Then you should use a regular expression. I think this would be something like :
var re = new RegExp("^DPObject([0-9]+)$");
re.test(someString);
This ensures there is at least only one digit after DPObject.
The "^" at the beginning is to ensure the string starts with DPObject. Check references on regexps for this kind of problems :)
edit: added "$" to mark the end of the string, the updated should be more "solid"
There are a couple of ways:
Use Javascripts indexOf method
Use Javascript Regular Expressions
Use JQuery's contains function
Regular expressions are the most powerful and elegant way of doing it. They syntax makes sense after a while (honestly). ;-)
Good luck.
We can work with escape sequence in strings on JavaScript. For example, I can write \\ and it means \. But I don't want to use a escape sequence.
I know that on C# I can write #"My string" and I don't need to escape anything. Is there similar syntax in JavaScript?
No, there's not. However, there are RegExp literals:
/foo\s+bar/
There is no such syntax, but there is a work around:
var string = (<r><![CDATA[
Now you can put a whole lot of stuff here.
Including new lines, and all sorts of symbols: \ " '
]]></r>).toString();
Because it's so verbose it's only worth using this when you have something that would be otherwise unreadable (eg: a pretty long string with a bunch of characters that need escaping).
Regex fun again...
Take for example http://something.com/en/page
I want to test for an exact match on /en/ including the forward slashes, otherwise it could match 'en' from other parts of the string.
I'm sure this is easy, for someone other than me!
EDIT:
I'm using it for a string.match() in javascript
Well it really depends on what programming language will be executing the regex, but the actual regex is simply
/en/
For .Net the following code works properly:
string url = "http://something.com/en/page";
bool MatchFound = Regex.Match(url, "/en/").Success;
Here is the JavaScript version:
var url = 'http://something.com/en/page';
if (url.match(/\/en\//)) {
alert('match found');
}
else {
alert('no match');
}
DUH
Thank you to Welbog and Chris Ballance to making what should have been the most obvious point. This does not require Regular Expressions to solve. It simply is a contains statement. Regex should only be used where it is needed and that should have been my first consideration and not the last.
If you're trying to match /en/ specifically, you don't need a regular expression at all. Just use your language's equivalent of contains to test for that substring.
If you're trying to match any two-letter part of the URL between two slashes, you need an expression like this:
/../
If you want to capture the two-letter code, enclose the periods in parentheses:
/(..)/
Depending on your language, you may need to escape the slashes:
\/..\/
\/(..)\/
And if you want to make sure you match letters instead of any character (including numbers and symbols), you might want to use an expression like this instead:
/[a-z]{2}/
Which will be recognized by most regex variations.
Again, you can escape the slashes and add a capturing group this way:
\/([a-z]{2})\/
And if you don't need to escape them:
/([a-z]{2})/
This expression will match any string in the form /xy/ where x and y are letters. So it will match /en/, /fr/, /de/, etc.
In JavaScript, you'll need the escaped version: \/([a-z]{2})\/.
You may need to escape the forward-slashes...
/\/en\//
Any reason /en/ would not work?
/\/en\// or perhaps /http\w*:\/\/[^\/]*\/en\//
You don't need a regex for this:
location.pathname.substr(0, 4) === "/en/"
Of course, if you insist on using a regex, use this:
/^\/en\//.test(location.pathname)