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

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

Related

jQuery regex replace return replacing word

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)

javascript regex Numbers and letters only

This should automatically remove characters NOT on my regex, but if I put in the string asdf sd %$##$, it doesnt remove anything, and if I put in this #sdf%#, it only removes the first character. I'm trying to make it remove any and all instances of those symbols/special characters (anything not on my regex), but its not working all the time. Thanks for any help:
function ohno(){
var pattern = new RegExp("[^a-zA-Z0-9]+");
var str = "#sdf%#"; //"asdf sd %$##$" // Try both
str = str.replace(pattern,' ');
document.getElementById('msg').innerHTML = str;
}
You need the g flag to remove more than one match:
var pattern = new RegExp("[^a-zA-Z0-9]+", "g");
Note that it would be more efficient and readable to use a regex literal instead of the RegExp constructor:
var pattern = /[^a-zA-Z0-9]+/g;
reference
You need to set global using "g", The flag indicates that the regular expression should be tested against all possible matches in a string.
new RegExp("[^a-zA-Z0-9]+", "g")
Reference
var pattern = new RegExp("[^a-zA-Z0-9]+", "g");
var str = "#sdf%#"; //"asdf sd %$##$" // Try both
str = str.replace(pattern,' ');
alert(str)

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("\\\[.*?\\\]|\\\(.*?\\\)");

how to config RegExp when string contains parentheses

I'm sure this is an easy one, but I can't find it on the net.
This code:
var new_html = "foo and bar(arg)";
var bad_string = "bar(arg)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
sets bad_start to -1 (not found). If I remove the (arg), it runs as expected (bad_start == 8). Is there something I can do to make the (very handy) "new Regexp" syntax work, or do I have to find another way? This example is trivial, but in the real app it would be doing global search and replace, so I need the regex and the "g". Or do I?
TIA
Escape the brackets by double back slashes \\. Try this.
var new_html = "foo and bar(arg)";
var bad_string = "bar\\(arg\\)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
Demo
Your RegEx definition string should be:
var bad_string = "bar\\(arg\\)";
Special characters need to be escaped when using RegEx, and because you are building the RegEx in a string you need to escape your escape character :P
http://www.regular-expressions.info/characters.html
You need to escape the special characters contained in string you are creating your Regex from. For example, define this function:
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
And use it to assign the result to your bad_string variable:
let bad_string = "bar(arg)"
bad_string = escapeRegex(bad_string)
// You can now use the string to create the Regex :v:

how to extract string part and ignore number in jquery?

I have a string like foobar1, foobaz2, barbar23, nobar100 I want only foobar, foobaz, barbar, nobar and ignoring the number part.
If you want to strip out things that are digits, a regex can do that for you:
var s = "foobar1";
s = s.replace(/\d/g, "");
alert(s);
// "foobar"
(\d is the regex class for "digit". We're replacing them with nothing.)
Note that as given, it will remove any digit anywhere in the string.
This can be done in JavaScript:
/^[^\d]+/.exec("foobar1")[0]
This will return all characters from the beginning of string until a number is found.
var str = 'foobar1, foobaz2, barbar23, nobar100';
console.log(str.replace(/\d/g, ''));
Find some more information about regular expressions in javascript...
This should do what you want:
var re = /[0-9]*/g;
var newvalue= oldvalue.replace(re,"");
This replaces al numbers in the entire string. If you only want to remove at the end then use this:
var re = /[0-9]*$/g;
I don't know how to do that in JQuery, but in JavaScript you can just use a regular expression string replace.
var yourString = "foobar1, foobaz2, barbar23, nobar100";
var yourStringMinusDigits = yourString.replace(/\d/g,"");

Categories

Resources