简体   繁体   中英

Omitting special characters from the string using Jquery

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("!-","");

小提琴: http//jsfiddle.net/neilheinrich/eYCjX/

You dont need jquery for this. You can use javascript regex. See this jsfiddle

var code = "BFhGlzT6FBkDr2Zndp0!-1309";

code = code.replace(/[!-]/g,"");

alert(code);

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, "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM