I can't figure out why my jquery replacement code wouldn't work.
I try to make the follow replacement:
http://mysite.com/_thumbs/0000312/0312718/0312718_$varm.jpg
I added '$var' to the position where I want to put a number, we can take '1' for now.
So I need to replace $var for 1.
What I tried;
var img = $('img', this).attr('src'); // I grabs the image url like above.
img.replace(/$var/, 1)
But nothing happens.
Thanks in advance!
Nick
The dollar sign is a special character in regular expressions.
img.replace(/\$var/, "1");
Escaping the $ with a backslash will tell JavaScript that you want it to match a dollar sign. Otherwise, $ means "match the end of the search string".
edit — also note that if you want the updated string you'll need to save the return value from calling .replace():
img = img.replace(/\$var/, "1");
(You can of course save the replacement results in a different variable.)
Related
I have this in a javascript/jQuery string (This string is grabbed from an html ($('#shortcode')) elements value which could be changed if user clicks some buttons)
[csvtohtml_create include_rows="1-10"
debug_mode="no" source_type="visualizer_plugin" path="map"
source_files="bundeslander_staple.csv" include cols="1,2,4" exclude cols="3"]
In a textbox (named incl_sc) I have the value:
include cols="2,4"
I want to replace include_cols="1,2,4" from the above string with the value from the textbox.
so basically:
How do I replace include_cols values here? (include_cols="2,4" instead of include_cols="1,2,4") I'm great at many things but regex is not one of them. I guess regex is the thing to use here?
I'm trying this:
var s = $('#shortcode').html();
//I want to replace include cols="1,2,4" exclude cols="3"
//with include_cols="1,2" exclude_cols="3" for example
s.replace('/([include="])[^]*?\1/g', incl_sc.val() );
but I don't get any replacement at all (the string s is same string as $("#shortcode").html(). Obviously I'm doing something really dumb. Please help :-)
In short what you will need is
s.replace(/include cols="[^"]+"/g, incl_sc.val());
There were a couple problems with your code,
To use a regex with String.prototype.replace, you must pass a regex as the first argument, but you were actually passing a string.
This is a regex literal /regex/ while this isn't '/actually a string/'
In the text you supplied in your question include_cols is written as include cols (with a space)
And your regex was formed wrong. I recomend testing them in this website, where you can also learn more if you want.
The code above will replace the part include cols="1,2,3" by whatever is in the textarea, regardless of whats between the quotes (as long it doesn't contain another quote).
First of all I think you need to remove the quotes and fix a little bit the regex.
const r = /(include_cols=\")(.*)(\")/g;
s.replace(r, `$1${incl_sc.val()}$3`)
Basically, I group the first and last part in order to include them at the end of the replacement. You can also avoid create the first and last group and put it literally in the last argument of the replace function, like this:
const r = /include_cols=\"(.*)\"/g;
s.replace(r, `include_cols="${incl_sc.val()}"`)
I am attempting to use the replace() function on a large amount of text, to filter out "[","{","(", and many other special characters. I initially attempted to just say:
replace(/"{"/g," ")
But this did not work, I tried a series of variations like this, using:
"/{/"g
or
"/{/g"
Yet, none of them worked. I have also tried attaching the first replace parameter to a variable as they do in the Mozilla tutorial.
var replacingStuff = /{/g;
str.replace(replacingStuff," ");
Does anyone have any ideas on how to fix this problem?
Use /[/[]/g as the regex to get rid of [
Basically, if you want to get rid of a certain character, it needs to be in brackets. For example, if you wanted to replace the characters a, b, and c, you would use the regex /[abc]/g.
You can use the snippet below. The regex pattern I used was /[[{(]/g. It may seem a bit overwhelming, but all it's doing is removing all the characters inside the bracket. Strip away the outside brackets and you get [{( which is the characters the regex will replace.
var text = "[fas[ds{ed[d{s(fasd[fa(sd"
console.log(text.replace(/[[{(]/g, ''));
I have to implement some type of pixel for analytic and it requires passing a session Id in the url string. My sessionID contains special characters. It looks something like this BFhGlzT6FBkDr2Zndp0!-1309
I need to remove the (-!) characters from this string, how do I achieve this using jquery? I need to make sure jquery remove those characters before it render otherwise it will not report a visit to analytic.
Guys thanks your help but maybe I need to explain bit further, my pixel code look some what like this "
img src="https://sometime.com/png?org_id=k8vif92&session_
id=T6PtTyRSqhGPYBhp84frwth67n6fL7wcLBFhGlzT6FBkDr2Zndp0!-130901808!1319637471144&m=2&m=2" alt="">
Before this pixel fire off, I need to replace the character in the sessionId string to remove !- and keep in mind session id will change every time there is a new session. I need a code that is generic so it works no matter what session id is, it needs to delete special characters from it.
Try using .replace:
var token = "BFhGlzT6FBkDr2Zndp0!-1309";
token.replace(/[^A-Za-z0-9]/g, "");
this will remove any character that's not a letter or number. More concisely:
token.replace(/\W/g, "");
(this won't replace underscores)
Black-listing ! and - (fiddle):
var url = "BFhGlzT6FBkDr2Zndp0!-1309";
document.write(url.replace(/[!\-]/g,""));
White-listing alpha-numeric (fiddle):
var url = "BFhGlzT6FBkDr2Zndp0!-1309";
document.write(url.replace(/[^a-z0-9]/ig,""));
var str = "BFhGlzT6FBkDr2Zndp0!-1309".replace("!-","");
fiddle: http://jsfiddle.net/neilheinrich/eYCjX/
Define a regular expression character set that contains all the allowed characters. For example, yours might look like /[a-zA-Z0-9]/. Now invert it with the complementary character set [^a-zA-Z0-9] and remove all those characters with the String.replace method.
mystring = mystring.replace(/[^a-zA-Z0-9]/g, "");
You dont need jquery for this. You can use javascript regex. See this jsfiddle
var code = "BFhGlzT6FBkDr2Zndp0!-1309";
code = code.replace(/[!-]/g,"");
alert(code);
I'm trying to remove a rectangular brackets(bbcode style) using javascript, this is for removing unwanted bbcode.
I try with this.
theString .replace(/\[quote[^\/]+\]*\[\/quote\]/, "")
it works with this string sample:
theString = "[quote=MyName;225]Test 123[/quote]";
it will fail within this sample:
theString = "[quote=MyName;225]Test [quote]inside quotes[/quote]123[/quote]";
if there any solution beside regex no problem
The other 2 solutions simply do not work (see my comments). To solve this problem you first need to craft a regex which matches the innermost matching quote elements (which contain neither [QUOTE..] nor [/QUOTE]). Next, you need to iterate, applying this regex over and over until there are no more QUOTE elements left. This tested function does what you want:
function filterQuotes(text)
{ // Regex matches inner [QUOTE]non-quote-stuff[/quote] tag.
var re = /\[quote[^\[]+(?:(?!\[\/?quote\b)\[[^\[]*)*\[\/quote\]/ig;
while (text.search(re) !== -1)
{ // Need to iterate removing QUOTEs from inside out.
text = text.replace(re, "");
}
return text;
}
Note that this regex employs Jeffrey Friedl's "Unrolling the loop" efficiency technique and is not only accurate, but is quite fast to boot.
See: Mastering Regular Expressions (3rd Edition) (highly recommended).
Try this one:
/\[quote[^\/]+\].*\[\/quote\]$/
The $ sign indicates that only the closing quote element at the end of the string should be used to determine the ending of the quote you're trying to remove.
And i added a "." before the asterisk so that this will match any sign in between. I tested this with your two strings and it worked.
edit: I don't exactly know how you are using that. But just as an addition. If you want the pattern also to match to a string where no attributes are added for example:
[quote]Hello[/quote]
You should change the "+" sign into an asterisk as well like this:
/\[quote[^\/]*\].*\[\/quote\]$/
This answer has flaws, see Ridgerunner's answer for a more correct one.
Here's my crack at it.
function filterQuotes(text)
{
return text.replace(/\[(\/)?quote([^\/]*)?\]/g,"");
}
I would like to convert any instances of a hashtag in a String into a linked URL:
#hashtag -> should have "#hashtag" linked.
This is a #hashtag -> should have "#hashtag" linked.
This is a [url=http://www.mysite.com/#name]named anchor[/url] -> should not be linked.
This isn't a pretty way to use quotes -> should not be linked.
Here is my current code:
String.prototype.parseHashtag = function() {
return this.replace(/[^&][#]+[A-Za-z0-9-_]+(?!])/, function(t) {
var tag = t.replace("#","")
return t.link("http://www.mysite.com/tag/"+tag);
});
};
Currently, this appears to fix escaped characters (by excluding matches with the amperstand), handles named anchors, but it doesn't link the #hashtag if it's the first thing in the message, and it seems to grab include the 1-2 characters prior to the "#" in the link.
Halp!
How about the following:
/(^|[^&])#([A-Za-z0-9_-]+)(?![A-Za-z0-9_\]-])/g
matches the hashtags in your example. Since JavaScript doesn't support lookbehind, it tries to either match the start of the string or any character except & before the hashtag. It captures the latter so it can later be replaced. It also captures the name of the hashtag.
So, for example:
subject.replace(/(^|[^&])#([A-Za-z0-9_-]+)(?![A-Za-z0-9_\]-])/g, "$1http://www.mysite.com/tag/$2");
will transform
#hashtag
This is a #hashtag and this one #too.
This is a [url=http://www.mysite.com/#name]named anchor[/url]
This isn't a pretty way to use quotes
into
http://www.mysite.com/tag/hashtag
This is a http://www.mysite.com/tag/hashtag and this one http://www.mysite.com/tag/too.
This is a [url=http://www.mysite.com/#name]named anchor[/url]
This isn't a pretty way to use quotes
This probably isn't what t.link() (which I don't know) would have returned, but I hope it's a good starting point.
There is an open-source Ruby gem to do this sort of thing (hashtags and #usernames) called twitter-text. You might get some ideas and regexes from that, or try out this JavaScript port.
Using the JavaScript port, you'll want to just do:
var linked = TwitterText.auto_link_hashtags(text, {hashtag_url_base: "http://www.mysite.come/tag/"});
Tim, your solution was almost perfect. Here's what I ended up using:
subject.replace(/(^| )#([A-Za-z0-9_-]+)(?![A-Za-z0-9_\]-])/g, "$1#$2");
The only change is the first conditional, changed it to match the beginning of the string or a space character. (I tried \s, but that didn't work at all.)