jQuery regex replace return replacing word - javascript

I have a string (url) like this:
https://8.random.url.com/g/DFGTER5675/test1/undefined/codec/
Here is my regex:
/https\:\/\/(?:.*)\/g\/(?:.*)\/(?:.*)\/(.*)\/codec\/(?:.*)/gi
And my code:
var string = "https://8.random.url.com/g/DFGTER5675/test1/undefined/codec/";
var myRegexp = /https\:\/\/(?:.*)\/g\/(?:.*)\/(?:.*)\/(.*)\/codec\/(?:.*)/gi
var match = string.replace(myRegexp, "OMEGA3");
When I do console.log(match) it returns only "OMEGA3". What I want is just my string with "undefined" replaced by "OMEGA3". What am I doing wrong? Thanks.

You can use this regex with capturing groups and back-reference:
url = url.replace(/(https?:\/\/[^\/]*\/g\/[^\/]*\/[^\/]*\/).*(\/codec\/)/gi, '$1OMEGA3$2');
RegEx Demo

You have the use of the capture group backwards. You should be capturing the parts of the pattern that you want to keep, not the part you want to replace. Then use $1, $2, etc. to copy those to the replacement.
You also have several non-capturing groups that aren't needed at all.
var myRegexp = /(https:\/\/.*\/g\/.*\/).*(\/codec\/)/gi
var match = string.replace(myRegexp, "$1OMEGA3$2");

why not use /undefined/gi
var string = "https://8.random.url.com/g/DFGTER5675/test1/undefined/codec/";
var myRegexp = /(https\:\/\/.*?\/.*?\/.*?\/.*?\/).*?(\/.*?\/)/gi
var match = string.replace(myRegexp, "$1OMEGA3$2");
console.log(match)

Related

Use regex to remove "public://" from string

Im lost in part of this.
I want to remove the public:// in every link of an image like public://china-taxi_4.jpg
I have tried this but returns null:
var _img = 'public://china-taxi_4.jpg';
var regex = /(public:)(\/\w+)/;
var matches = _img.match(regex);
console.log(matches);
Hope you can help.
I want to remove the 'public://' in every link of an image.
> var img = 'public://china-taxi_4.jpg';
> img.replace(/public:\/\/(?=\S+?\.jpg(?:\s|$))/, "")
'china-taxi_4.jpg'
It removes the word public:// only in the strings which ends with .jpg
You are removing a literal string, not a regular expression. So try:
var _img = 'public://china-taxi_4.jpg';
var result = _img.replace("public://","");
console.log(result);
Regexes are for matching complex expressions.
I think you're missing a slash, try:
var _img = 'public://china-taxi_4.jpg';
var regex = /(public:)(\/\/\w+)/;
var matches = _img.match(regex);
console.log(matches);
From Mozilla Developer Network String.prototype.replace():
Example: Defining the regular expression in replace()
In the following example, the regular expression is defined in
replace() and includes the ignore case flag.
var str = 'Twas the night before Xmas...';
var newstr = str.replace(/xmas/i, 'Christmas');
console.log(newstr);
This prints:
'Twas the night before Christmas...'
To match the beginning of a string, use ^
To escape characters that have special meaning in regexp like : and / so that regexp will match these literally, prepend \
This suggests:
var _img = 'public://china-taxi_4.jpg';
var newimg = _img.replace(/^public\:\/\//i, '');
Tested and working in chrome browser console window.
Note: This answer also matches an earlier comment by #dystroy, so I have marked it CW.
var re = /(public:)(\/\/[\w-.]+)/g;
See demo.
http://regex101.com/r/rA7aS3/9

Passing Parameter into function match

I am using the function match for a search engine, so whenever a user types a search-string I take that string and use the match function on an array containing country names, but it doesn't seem to work.
For example if I do :
var string = "algeria";
var res = string.match(/alge/g); //alge is what the user would have typed in the search bar
alert(res);
I get a string res = "alge": //thus verifying that alge exists in algeria
But if I do this, it returns null, why? and how can I make it work?
var regex = "/alge/g";
var string = "algeria";
var res = string.match(regex);
alert(res);
To make a regex from a string, you need to create a RegExp object:
var regex = new RegExp("alge", "g");
(Beware that unless your users will be typing actual regular expressions, you'll need to escape any characters that have special meaning within regular expressions - see Is there a RegExp.escape function in Javascript? for ways to do this.)
You don't need quotes around the regex:
var regex = /alge/g;
Remove the quotes around the regex.
var regex = /alge/g;
var string = "algeria";
var res = string.match(regex);
alert(res);
found the answer, the match function takes a regex object so have to do
var regex = new RegExp(string, "g");
var res = text.match(regex);
This works fine

Regex working fine in C# but not in Javascript

I have the following javascript code:
var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]"
var latexRegex = new RegExp("\\\[.*\\\]|\\\(.*\\\)");
var matches = latexRegex.exec(markdown);
alert(matches[0]);
matches has only matches[0] = "x=1 and y=2" and should be:
matches[0] = "\(x=1\)"
matches[1] = "\(y=2\)"
matches[2] = "\[z=3\]"
But this regex works fine in C#.
Any idea why this happens?
Thank You,
Miguel
Specify g flag to match multiple times.
Use String.match instead of RegExp.exec.
Using regular expression literal (/.../), you don't need to escape \.
* matches greedily. Use non-greedy version: *?
var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]"
var latexRegex = /\[.*?\]|\(.*?\)/g;
var matches = markdown.match(latexRegex);
matches // => ["(x=1)", "(y=2)", "[z=3]"]
Try non-greedy: \\\[.*?\\\]|\\\(.*?\\\). You need to also use a loop if using the .exec() method like so:
var res, matches = [], string = 'I have \(x=1\) and \(y=2\) and even \[z=3\]';
var exp = new RegExp('\\\[.*?\\\]|\\\(.*?\\\)', 'g');
while (res = exp.exec(string)) {
matches.push(res[0]);
}
console.log(matches);
Try using the match function instead of the exec function. exec only returns the first string it finds, match returns them all, if the global flag is set.
var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]";
var latexRegex = new RegExp("\\\[.*\\\]|\\\(.*\\\)", "g");
var matches = markdown.match(latexRegex);
alert(matches[0]);
alert(matches[1]);
If you don't want to get \(x=1\) and \(y=2\) as a match, you will need to use non-greedy operators (*?) instead of greedy operators (*). Your RegExp will become:
var latexRegex = new RegExp("\\\[.*?\\\]|\\\(.*?\\\)");

regex: any string between two slashes first of them is prefixed with a defined string

I'd like to get the talker name of some mp3s files paths such as the following:
/assets/audio/James_Lee/001.mp3
/assets/audio/Marc_Smith/001.mp3
/aasets/audio/blahblah/001.mp3
In the previous example we note that each talker name is surrounded by two slashes where the first of them is prefixed with the word audio. I need a pattern that matches names like the example above using javascript.
I tried at http://regexpal.com/ :
audio/.*/
but it only matches *audio/The_name/* where I need *The_name* only. The other thing I don't know how could I use such patterns with javascript replace().
This will get your the name: (?<=\/assets\/audio\/).*(?=\/)
Here's the regex in use: http://regexr.com?34747
Considering Javascript, you could do this:
var string = "/assets/audio/James_Lee/001.mp3";
var name = string.replace(/^.*\/audio\/|\/[\d]+\..*$/g, '');
Try this:
var str = "/assets/audio/James_Lee/001.mp3\n/assets/audio/Marc_Smith/001.mp3";
var pattern = /audio\/(.+?)\//g;
var match;
var matches = [];
while ((match = pattern.exec(str)) !== null){
matches.push(match[1]);
}
console.log(matches);
// If you want a string with only the names, you can re-combine the matches
str = matches.join('\n');
how about this?
str.replace(/.*audio\/([^\/]*)\/.*/,"$1")

Shouldn't this RegExp work?

testString = "something://something/task?type=Checkin";
patt = new RegExp("something\/(\w*)\?");
match = patt.exec(testString);
document.querySelector('#resultRegexp').innerHTML = match[1];
I want to capture task So shouldn't this RegExp work?
I am grabbing any alphanumeric character up until the question mark... and capturing it.
http://jsfiddle.net/h4yhc/2/
You would need to escape the slash in regex literals, and the backslash in string literals which you create regexes from:
var patt = /something\/(\w*)\?/g;
// or
var patt = new RegExp("something/(\\w*)\\?", 'g');
I strongly recommend the first version, it is more readable.
I think this would be enough: (\w*)\?, since / is not captured by \w and the only ? in the string is after your target string.
This is what you need:
patt = new RegExp(".*/(\\w*)\\?");
http://jsfiddle.net/FJcfd/
try with this: var pat = /something:\/\/(?:[^\/]+\/)+(\w+)\?(\w+=\w+)/;
it can match string such as:
something://something/task?type=Checkin
something://something/foo/task?type=Checkin
something://something/foo/bar/task1?type3=Checkin4

Categories

Resources