replace / with "" and " " with %20 in one go on a javascript variable? - javascript

I insert some strings in an array but before I do that I want to do what topic says. To only replace space with %20 I do:
Name.push(linkText.replace(" ", "%20"));
But how do I perform two "replace" there in one go?
Thanks in advance

It looks to me like you are trying to encode plaintext to use it in a URL or query string. I suspect you would be better off using one of javascript's built-in encoding methods, encodeURI or encodeURIComponent. See:
http://www.javascripter.net/faq/escape.htm

Do you want to replace two spaces in a row with one %20?
Name.push(linkText.replace(/ +/g, "%20"));
Or do you want to replace 2 spaces with %20%20?
Name.push(linkText.replace(/ /g, "%20"));

You could do something like this:
Name.push(linkText.replace(" ", "%20").replace("/", ""));

You can't do it using a single function call in regular JavaScript.
You could do this:
Name.push(linkText.replace(" ", "%20").replace("/", ""));

Related

How to encode a search query with javascript

If I search for How to Format i get
How%20to%20Format
but I want to be How-to-Format
window.location = '/search/'+encodeURIComponent(query);
also escape(), encodeURI() dont work
Try like this:
window.location = '/search/'+ query.replace(/\s+/gi, '-');
Working example with stripping multi-spaces into one:
http://jsfiddle.net/VVEpE/
encodeURIComponent (and the broken, deprecated escape) will convert space characters to representations of a space that you can put in a URI.
If you want to use custom slug generation rules then you will have to write them yourself, probably using a regular expression.
e.g.
query.replace(/\s/g, "-");
string.replace(searchvalue,newvalue)
in this case
window.location = '/search/'+query.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);

Escape Characters in JavaScript Function for Double quote

I have a web application where I am dynamically creating a url. The url has a parameter and I must pass a double quote. I have tried this all different ways but it is still not working. Anybody have any ideas?
To create the URL:
searchSurveyDetail.setSurveyFormURL(surveyDetail.getSurveyFormURL()+"#search="+ "\"" + searchValue + "\"");
on the Page:
onClick="window.open('${surveyDetail.surveyInstructionsURL}')"
The result:
onClick="window.open('http://www.mytest.com/survey1.pdf#search="company"')"
The short answer is you need to double escape the double quotes. So you need:
searchSurveyDetail.setSurveyFormURL(surveyDetail.getSurveyFormURL()+"#search="+ "\\\"" + searchValue + "\\\"");
which produces:
onClick="window.open('http://www.mytest.com/survey1.pdf#search=\"company\"')"
which will escape the quotes properly.
Couple of things to keep in mind:
This doesn't take care of double quotes in the search term itself. Make sure you escape that.
I'm not sure why you want to wrap the search term in double quotes. For a typical search url, you'll want a query string like: search=term not search="term" because you'll just end up stripping the quotes later. But maybe you need that for some reason.
I gather you're using PHP on the server side? In that case you should run the URL through htmlspecialchars() before concatenating it to the HTML.

How do you replace a pound (currency) sign in 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.

REGEX: Appending Single Space between Capitals in Javascript

I got some idea from a C# related thread, but I need it in Javascript. I am try all sorts of things, it doesn't seem to work.
name.replace(/[A-Z]/g, / $&/);
What I am trying to do is make:
FirstName
with spaces:
First Name
But what I get is:
/ F/irst/ N/ame
Any ideas would be much appreciated.
"FirstName".replace(/([a-z])([A-Z])/g, '$1 $2')
That results in
First Name
Without a leading space.
s.replace(/[A-Z]/g, ' $&')
The second parameter need not be a regex, but a string instead.
Remove the / from the replace section. Some languages need them, some don't.

Categories

Resources