I have no idea what is happening here..
model.attributes.data.Path.replace('/\\/g',""), #options.path.replace('/\\/g',"")
When doing :
console.log model.attributes.data.Path.replace('/\\/g',""),
#options.path.replace('/\\/g',"")
the data is:
T2/T2_2, T2/T2_2
It returns this:
T2T2_2, T2/T2_2
So only the first path was replaced, but not the second one? Why would that be?
Aside from the fact you're matching backslashes (\\ = \), instead of forward slashes (\/ = /), Don't put your regexes into the replace function as strings.
Use:
.replace(/\//g,"");
Instead of
.replace('/\//g',"");
Then it'll work just fine:
"T2/T2_2 , T2/T2_2".replace(/\//g,"");
// returns: "T2T2_2 , T2T2_2"
Otherwise, it'll just try to literally find the string '/\//g'.
Also, to replace both forward and backslashes in 1 regex, try this:
"T2/T2_2 , T2\T2_2".replace(/\/|\\/g,"");
// returns: "T2T2_2 , T2T2_2"
# \/|\\ Matches:
# \/ - Forward slash
# | - Or
# \\ - Backslash
Try .replace(/\//g,"") instead of .replace('/\\/g',""), (the regex is not a string).
Try:
model.attributes.data.Path.replace(/\//g,"")
#options.path.replace(/\//g,"")
/\\/g matches a backslash and /\//g matches a forward slash.
Related
I am trying to create a Regexp in JS that only look into string having files and ignore the paths which don't have a filename.
input
tanxe\src\lib\hello
tanxe\lib\hello\world\verboseBackup.js
tanxe\src\hello\verboseBackup.js
tanxe\lib\verboseBackup.js
Trying
input.match(/^tanxe.*?lib.*?\\..*/i)
Expected Output:
tanxe\lib\hello\world\verboseBackup.js
tanxe\lib\verboseBackup.js
You can try this mate
^.*\.\w+$
Explanation
^ - Anchor to start of string.
.* - Matches anything one or more times except newline character.
\. - Matches ..
\w+ - Matches word character one or more time.
$ - End of string.
Demo
Update:- In case you strictly want to match tanxe\lib and followed things only
You can try this mate
^tanxe\\lib\\.+\.\w+$
Demo
You might try this: tanxe\\lib.*?\.\w+
It matches paths starting with tanxe\lib and ending with a file extension.
input.match(/^tanxe\\lib\\(\w+\\)*\w+\.\w+/gi);
See the regExr fiddle I created.
Your regex is work, I think you need is additional flags: g global, m multiline
var input = `tanxe\\src\\lib\\hello
tanxe\\lib\\hello\\world\\verboseBackup.js
tanxe\\src\\hello\\verboseBackup.js
tanxe\\lib\\verboseBackup.js
D:\\Program Files\\atom\\.atom\\packages\\utilities-tanxe\\lib\\abc\\verboseBackup.js`
input.match(/^.*tanxe.*?lib.*?\..*/gmi).forEach(r => console.log(r))
// start with "tanxe"
//input.match(/^tanxe.*?lib.*?\..*/gmi).forEach(r => console.log(r))
Try this one too.
tanxe\\[a-zA-Z\\]+[.]{1}[a-zA-z]{2,3}
I want to remove size data from a file name like
var src = 'http://az648995.vo.msecnd.net/win/2015/11/Halo-1024x551.jpg';
src = src.replace(
/-\d+x\d+(.\S+)$/,
function( match, contents, offset, s ) {
return contents;
}
);
this works as expected and i get
http://az648995.vo.msecnd.net/win/2015/11/Halo.jpg
But if I have a filename like
http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.jpg
it returns
http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-1024x512.jpg
instead of the desired
http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000.jpg
Your regex does not work as expected primarily because of an unescaped dot in (.\S+)$ part. An unescaped . matches any character but a newline. However, \S matches any non-whitespace, including a .. Besides unnecessary backtracking, you may get an unexpected result with a string like http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.MORE_TEXT_HERE.jpg.
Assuming the extension is the part of a string after the last dot, you can use
-\d+x\d+(\.[^.\s]+)$
See regex demo
The nagated character class [^.\s] matches any character but whitespace and a literal . symbol. Note that there is no point in using a callback function inside a replace, you can use a mere $1 backreference.
JS demo:
var src = 'http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.jpg';
src = src.replace(/-\d+x\d+(.[^.\s]+)$/, "$1");
document.body.innerHTML = src;
Try escaping the . and you will be fine:
/-\d+x\d+(\.\S+)$/
Slightly change the regex to be a little more explicit:
/-\d+x\d+(\.[^\s-]+)$/
The regex can be simplified to the following
Replace
-\d+x\d+(\.\S+)
With
$1
I'm working with a Google API that returns IDs in the below format, which I've saved as a string. How can I write a Regular Expression in javascript to trim the string to only the characters after the last slash in the URL.
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'
Don't write a regex! This is trivial to do with string functions instead:
var final = id.substr(id.lastIndexOf('/') + 1);
It's even easier if you know that the final part will always be 16 characters:
var final = id.substr(-16);
A slightly different regex approach:
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
Breaking down this regex:
\/ match a slash
( start of a captured group within the match
[^\/] match a non-slash character
+ match one of more of the non-slash characters
) end of the captured group
\/? allow one optional / at the end of the string
$ match to the end of the string
The [1] then retrieves the first captured group within the match
Working snippet:
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9';
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
// display result
document.write(afterSlashChars);
Just in case someone else comes across this thread and is looking for a simple JS solution:
id.split('/').pop(-1)
this is easy to understand (?!.*/).+
let me explain:
first, lets match everything that has a slash at the end, ok?
that's the part we don't want
.*/ matches everything until the last slash
then, we make a "Negative lookahead" (?!) to say "I don't want this, discard it"
(?!.*) this is "Negative lookahead"
Now we can happily take whatever is next to what we don't want with this
.+
YOU MAY NEED TO ESCAPE THE / SO IT BECOMES:
(?!.*\/).+
this regexp: [^\/]+$ - works like a champ:
var id = ".../base/nabb80191e23b7d9"
result = id.match(/[^\/]+$/)[0];
// results -> "nabb80191e23b7d9"
This should work:
last = id.match(/\/([^/]*)$/)[1];
//=> nabb80191e23b7d9
Don't know JS, using others examples (and a guess) -
id = id.match(/[^\/]*$/); // [0] optional ?
Why not use replace?
"http://google.com/aaa".replace(/(.*\/)*/,"")
yields "aaa"
I´m trying to get the first part of a hash from a url (the part between the # and a /, a ? or the end of the string
So far now I came out with this:
r = /#(.*)[\?|\/|$]/
// OK
r.exec('http://localhost/item.html#hash/sub')
["#hash/", "hash"]
// OK
r.exec('http://localhost/item.html#hash?sub')
["#hash?", "hash"]
// WAT?
r.exec('http://localhost/item.html#hash')
null
I was expeting to receive "hash"
I tracked down the problem to
/#(.*)[$]/
r2.exec('http://localhost/item.html#hash')
null
any idea what could be wrong?
r = /#(.*)[\?|\/|$]/
When $ appears in [] (character class, it's the literal "$" character, not the end of input/line. In fact, your [\?|\/|$] part is equivalent to just [?/$|], which matches the 4 specific characters (including pipe).
Use this instead (JSFiddle)
r = /#(.+?)(\?|\/|$)/
You aren't supposed to write [$] (within a character class) unless you want to match the $ literally and not the end of line.
/#(.*)$/
Code:
var regex = /\#(.*)$/;
regex.exec('http://localhost/item.html#hash');
Output:
["#hash", "hash"]
Your regex: /#(.*)[\?|\/|$]/
//<problem>-----^ ^-----<problem>
| operator won't work within [], but within ()
$ will be treated literally within []
.* will match as much as possible. .*? will be non-greedy
On making the above changes,
you end up with /#(.*?)(\?|\/|$)/
I use http://regexpal.com/ to test my regular expressions.
Your problem here is that your regular expression wants a /. So it don't works with http://localhost/item.html#hash but it works with http://localhost/item.html#hash/
Try this one :
r = /#([^\?|\/|$]*)/
You can't use the $ end-of-string marker in a character class. You're probably better off just matching characaters that aren't / or ?, like this:
/#([^\?\/]*)/
Why Regex? Do it like this (nearly no regex):
var a = document.createElement('a');
a.href = 'http://localhost/item.html#hash/foo?bar';
console.log(a.hash.split(/[\/\?]/)[0]); // #hash
Just for the sake, if it is node.js you are working with:
var hash = require('url').parse('http://localhost/item.html#hash').hash;
I found this regular expression that seems to work
r = /#([^\/\?]*)/
r.exec('http://localhost/item.html#hash/sub')
["#hash", "hash"]
r.exec('http://localhost/item.html#hash?sub')
["#hash", "hash"]
r.exec('http://localhost/item.html#hash')
["#hash", "hash"]
Anyway, I still don't get why the original one isn't working
For instance, I am using a simple regex to match everything before the first space:
var str = '14:00:00 GMT';
str.match(/(.*?)\s/)[0]; //Returns '14:00:00 ' note the space at the end
To avoid this I can do this:
str.match(/(.*?)\s/)[0].replace(' ', '');
But is there a better way? Can I just not include the space in the regex? Another examle is finding something between 2 characters. Say I want to find the 00 in the middle of the above string.
str.match(/:(.*?):/)[0]; //Returns :00: but I want 00
str.match(/:(.*?):/)[0].replace(':', ''); //Fixes it, but again...is there a better way?
I think you just need to change the index from 0 to 1 like this:
str.match(/(.*?)\s/)[1]
0 means the whole matched string, and 1 means the first group, which is exactly what you want.
#codaddict give another solution.
str.match(/(.*?)(?=\s)/)[0]
(?=\s) means lookahead but not consume whitespace, so the whole matched string is '14:00:00' but without whitespace.
You can use positive lookahead assertions as:
(.*?)(?=\s)
which says match everything which is before a whitespace but don't match the whitespace itself.
Yes there is, you can use character classes:
var str = '14:00:00 GMT';
str.match(/[^\s]*/)[0]; //matches everything except whitespace
Your code is quite close to the answer, you just need to replace [0] with [1].
When str.match(/:(.*?):/) is executed, it returns an object, in this example, the object length is 2, it looks like this:
[":00:","00"]
In index 0, it stores the whole string that matches your expression, in index 1 and later, it stores the result that matches the expression in each brackets.
Let's see another example:
var str = ":123abcABC:";
var result = str.match(/:(\d{3})([a-z]{3})([A-Z]{3}):/);
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);
console.log(result[3]);
And the result:
:123abcABC:
123
abc
ABC
Hope it's helpful.
Try this,
.*(?=(\sGMT))
RegexBuddy ScreenShot