How do you replace a pound (currency) sign in javascript? - javascript

I'm trying to remove a pound sign (£) from a string using javascript. I'm trying to do it using
str = str.replace(/\£/g, "");
However, it is not removing the sign.
The value of str is being fetched from a span (and the correct value is being fetched). This span has been previously set using javascript, with it being encoded in the string as
£
Any ideas on the best way to remove the pound sign?

You may need to use unicode for this. E.g., '£10.00'.replace(/\u00A3/g, '');

This way it works for me:
var str = "£sdfsdf";
str = str.replace("£", "");
alert(str);
Fiddle here: http://jsfiddle.net/peUrn/1/

Remove the backslash from your regexp.

You can just do
"hello w£orld".replace(/£/g,"")

The easy way is:
str.replace('£', '');

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, or three escape sequences representing the UTF-8 encoding of the character
Which means, in order to encode a pound sign, JavaScript uses 2 characters.
£ = %C2%A3
See http://fyneworks.blogspot.com/2008/06/british-pound-sign-encoding-revisited.html for more information.
It would be best to use %C2%A3 in place of the pound sign in your script.

Related

How to use a javascript Regex to globally find and replace the beginning of a string from a textarea

I am trying to replace any non encoded ampersands in a string in JavaScript and was wondering if this was possible. I have the regex build to detect this in the string, but when I do a replace, I will lose the parameter name.
Current input:
http://www.somesite.com/id/2343?paramA=1&paramB=asdf
From a textarea
<textarea id='test-box'>http://www.somesite.com/id/2343?paramA=1&paramB=asdf</textarea>
var str = $('#test-box').val();;
var regex = /&[a-z]+=/gi;
str = str.replace(regex, [REPLACE &'s WITH &'s]);
console.log(str);
Desired output:
http://www.somesite.com/id/2343?paramA=1&paramB=asdf
How can I then use JavaScript to keep the name of the parameter and simply replace the '&' with '&'?
Try this regex: /&(?=[a-z]+=)/ and this replacement: &
This uses a lookahead assertion rather than eating up the parameter name.
If you have a URL which might be partially encoded in HTML, and you're trying to make a best effort at producing XHTML validating textarea content, then you can use the list of HTML character references to identify ampersands which are not part of an HTML character reference:
str.replace(/&(?!#(?:[0-9]|[xX][0-9A-Fa-f])|lt;|gt;|amp|...)/g, '&')
where ... is replaced with the set of entities from that list that you care to recognize.
Note that most of those character references end in semicolon, so are not allowed to be followed immediately by an equals sign, so are not ambiguous with URL parameters. Only certain entities can appear without a semicolon for backwards compatibility.
If you don't care about validating, then you can just let the browser take care of it by ensuring that your URL doesn't contain the substring </textarea by doing something like
str.replace(/</g, '%3c')
Apart from lookahead assert, you can also use a backreference:
var regex = /&([a-z]+)=/gi;
str = str.replace(/&([a-z]+)=/gi,'&$1');
When $n appears in the replace string, it will be replaced by the n'th parenthesized pattern in the regexp.
Who needs regex when you've got jQuery html(). Especially since you've got a jquery tag on your question :D
What this does is leverage the browser's innerHTML property. see api
Fiddle
var str = 'http://www.somesite.com/id/2343?paramA=1&paramB=asd';
$('#test-box').text(str);
$('#html-box').text($('#test-box').html());

Javascript Replace via RegEx

I am trying to replace 3 chars with 3 other chars to build/mask an email address for a form.
This works only once or on the first instance of finding it:
email = "email1#domain!com|email2#domain!com|email3#domain!com";
email.replace("#","#").replace("!",".").replace("|",",");
The above code resulted in: email1#domain.com,email2#domain!com|email3#domain!com
After some reading I read about using RegEx which is the portion of coding I can never wrap my head around:
email.replace("/#/g","#").replace("/!/g",".").replace("/|/g",",");
That didn't work either and left it the same as the original var.
What am I doing wrong?
Do not put quotes around the regex. Regexes are literals that use / as a boundary.
Additionally, you will need to escape the | because it has a special meaning.
Finally, .replace is not transformative. It returns the result.
email = email.replace(/#/g,'#').replace(/!/g,'.').replace(/\|/g,',');
Using regex literals, you omit the quotes (and you'll need to escape the pipe):
email.replace(/#/g,"#").replace(/!/g,".").replace(/\|/g,",");
email = "email1#domain!com|email2#domain!com|email3#domain!com";
email=email.replace(/#/g,"#").replace(/!/g,".").replace(/\|/g,",");

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

Say I have a string variable (var str) as follows-
Dude, he totally said that "You Rock!"
Now If I'm to make it look like as follows-
Dude, he totally said that "You Rock!"
How do I accomplish this using the JavaScript replace() function?
str.replace("\"","\\""); is not working so well. It gives unterminated string literal error.
Now, if the above sentence were to be stored in a SQL database, say in MySQL as a LONGTEXT (or any other VARCHAR-ish) datatype, what else string optimizations I need to perform?
Quotes and commas are not very friendly with query strings. I'd appreciate a few suggestions on that matter as well.
You need to use a global regular expression for this. Try it this way:
str.replace(/"/g, '\\"');
Check out regex syntax and options for the replace function in Using Regular Expressions with JavaScript.
Try this:
str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)
Or, use single-quotes to quote your search and replace strings:
str.replace('"', '\\"'); // (Still need to escape the backslash)
As pointed out by helmus, if the first parameter passed to .replace() is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g (global) flag:
str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');
But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:
var str = "Dude, he totally said that \"You Rock!\"";
But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.
Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.
The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.
To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:
var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);

Remove a long dash from a string in JavaScript?

I've come across an error in my web app that I'm not sure how to fix.
Text boxes are sending me the long dash as part of their content (you know, the special long dash that MS Word automatically inserts sometimes). However, I can't find a way to replace it; since if I try to copy that character and put it into a JavaScript str.replace statement, it doesn't render right and it breaks the script.
How can I fix this?
The specific character that's killing it is —.
Also, if it helps, I'm passing the value as a GET parameter, and then encoding it in XML and sending it to a server.
This code might help:
text = text.replace(/\u2013|\u2014/g, "-");
It replaces all – (–) and — (—) symbols with simple dashes (-).
DEMO: http://jsfiddle.net/F953H/
That character is call an Em Dash. You can replace it like so:
str.replace('\u2014', '');​​​​​​​​​​
Here is an example Fiddle: http://jsfiddle.net/x67Ph/
The \u2014 is called a unicode escape sequence. These allow to to specify a unicode character by its code. 2014 happens to be the Em Dash.
There are three unicode long-ish dashes you need to worry about: http://en.wikipedia.org/wiki/Dash
You can replace unicode characters directly by using the unicode escape:
'—my string'.replace( /[\u2012\u2013\u2014\u2015]/g, '' )
There may be more characters behaving like this, and you may want to reuse them in html later. A more generic way to to deal with it could be to replace all 'extended characters' with their html encoded equivalent. You could do that Like this:
[yourstring].replace(/[\u0080-\uC350]/g,
function(a) {
return '&#'+a.charCodeAt(0)+';';
}
);
With the ECMAScript 2018 standard, JavaScript RegExp now supports Unicode property (or, category) classes. One of them, \p{Dash}, matches any Unicode character points that are dashes:
/\p{Dash}/gu
In ES5, the equivalent expression is:
/[-\u058A\u05BE\u1400\u1806\u2010-\u2015\u2053\u207B\u208B\u2212\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u2E5D\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]|\uD803\uDEAD/g
See the Unicode Utilities reference.
Here are some JavaScript examples:
const text = "Dashes: \uFF0D\uFE63\u058A\u1400\u1806\u2010-\u2013\uFE32\u2014\uFE58\uFE31\u2015\u2E3A\u2E3B\u2053\u2E17\u2E40\u2E5D\u301C\u30A0\u2E1A\u05BE\u2212\u207B\u208B\u3030𐺭";
const es5_dash_regex = /[-\u058A\u05BE\u1400\u1806\u2010-\u2015\u2053\u207B\u208B\u2212\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u2E5D\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]|\uD803\uDEAD/g;
console.log(text.replace(es5_dash_regex, '-')); // Normalize each dash to ASCII hyphen
// => Dashes: ----------------------------
To match one or more dashes and replace with a single char (or remove in one go):
/\p{Dash}+/gu
/(?:[-\u058A\u05BE\u1400\u1806\u2010-\u2015\u2053\u207B\u208B\u2212\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u2E5D\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]|\uD803\uDEAD)+/g

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

Categories

Resources