Escape quotes on string javascript [duplicate] - javascript

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I have a variable with this kind of string: 4.5"x8.5"x0.5"
I found many answers about how to escape the quotes, so I write this function:
function replaceQuotesChars (str)
{
var s = str.trim();
// s.replace('"','"');
// s.replace('"','\\"');
// s.replace(/\"/g,'\\"');
s.replace(/\"/g,'"');
return s;
};
But none of those help me to escape the quotes because I get the same string that I submit to the function.
I save that variable with a stringify object to the database so when I parse back the string I get an error.
What I'm doing wrong? Please help me.

After a .replace (or really just about any other string manipulation method) a new string is returned because strings are "immutable" objects (can't be modified once created). Your code assumes the operation happens "in-place". You need to capture the new string (which incidentally, you did do with the .trim() operation).
In the following code:
First .trim() is called on str, which copies the string in str but without the leading and trailing spaces, and then returns that new string.
On that new string, .replace() is called, which copies the trimmed string, but with the characters replaced and then returns a new string.
That final string is what is then returned by the function.
function replaceQuotesChars (str, delimeter) {
// Each string operation returns a new string. Take that final
// string and return it
return str.trim().replace(/\"/g, delimeter);
};
console.log(replaceQuotesChars('10.5" x 4.75"', """));
console.log(replaceQuotesChars('10.5" x 4.75"', "\'"));
console.log(replaceQuotesChars('10.5" x 4.75"', "\""));

#Scott Marcus has already answered the question but if you are confused using regex(like me) there is an alternate method using the .split() method.
var a = str.split("\"");
var newS=""
for(var i = 0; i<a.length; i++){
if(a[1]!= ""){
newS = newS + a[i];
}
}
return newS;
This runs slower than regex but does the job.

Related

Replace specific parameters [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 3 years ago.
I have this
var date = $('#Date').val();
this get the value in the textbox what would look like this
12/31/2009
Now I do this on it
var id = 'c_' + date.replace("/", '');
and the result is
c_1231/2009
It misses the last '/' I don't understand why though.
You need to set the g flag to replace globally:
date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')
Otherwise only the first occurrence will be replaced.
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String in as the string-to-match argument to the string.replace method, it doesn't do a string replace. It converts the string to a RegExp and does a regex substitution. As Gumbo explains, a regex substitution requires the g‍lobal flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
You can use:
String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
return this.toString();
}
return this.split(search).join(replace);
}

Unable to replace multiple occurrence of special symbol in a string [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 3 years ago.
I have this
var date = $('#Date').val();
this get the value in the textbox what would look like this
12/31/2009
Now I do this on it
var id = 'c_' + date.replace("/", '');
and the result is
c_1231/2009
It misses the last '/' I don't understand why though.
You need to set the g flag to replace globally:
date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')
Otherwise only the first occurrence will be replaced.
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String in as the string-to-match argument to the string.replace method, it doesn't do a string replace. It converts the string to a RegExp and does a regex substitution. As Gumbo explains, a regex substitution requires the g‍lobal flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
You can use:
String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
return this.toString();
}
return this.split(search).join(replace);
}

Removing any character besides 0-9 + - / * and ^ [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I'm trying to further my understanding of regular expressions in JavaScript.
So I have a form that allows a user to provide any string of characters. I'd like to take that string and remove any character that isn't a number, parenthesis, +, -, *, /, or ^. I'm trying to write a negating regex to grab anything that isn't valid and remove it. So far the code concerning this issue looks like this:
var pattern = /[^-\+\(\)\*\/\^0-9]*/g;
function validate (form) {
var string = form.input.value;
string.replace(pattern, '');
alert(string);
};
This regex works as intended on http://www.infobyip.com/regularexpressioncalculator.php regex tester, but always alerts with the exact string I supply without making any changes in the calculator. Any advice or pointers would be greatly appreciated.
The replace method doesn't modify the string. It creates a new string with the result of the replacement and returns it. You need to assign the result of the replacement back to the variable:
string = string.replace(pattern, '');

Javascript replace() function [duplicate]

This question already has answers here:
Replace function not replacing [duplicate]
(2 answers)
Closed 8 years ago.
This is a simple replace() question - and I can't get it working to replace a substring in the function below.
function linkOnClick(){
var anyNameYouLike = 'some sort of text/string right here';
anyNameYouLike.replace('right','in');
alert(anyNameYouLike)
}
It should return "some sort of text/string in here" but doesn't. What am I doing wrong? I'm fairly new with Javascript (if it isn't obvious...)
anyNameYouLike = anyNameYouLike.replace('right','in');
In javascript, strings are immutable (they are never modified). As such, the .replace() function does not modify the string you call it on. Instead, it returns a new string. So, if you want anyNameYouLike to contain the modified string, you have to assign the result to it like this:
anyNameYouLike = anyNameYouLike.replace('right','in');
For more info, refer to the MDN description of the .replace() method which says this:
Returns a new string with some or all matches of a pattern replaced by
a replacement. The pattern can be a string or a RegExp, and the
replacement can be a string or a function to be called for each match.
And, in the description of the .replace() method, it says this:
This method does not change the String object it is called on. It
simply returns a new string.

Replacing a colon using string replace using Javascript and jQuery [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I have a simple string that I'm trying to manipulate:
Your order will be processed soon:
I grab the string using:
var html = jQuery('.checkout td h4').html();
I then try to replace the ':' using:
html.replace(":", ".");
When I print it out to the console, the string is the same as the original string. I've also tried making sure that the html variable is of type "string" by doing the following:
html = html + "";
That doesn't do anything. In searching around, it seems that the replace function does a RegEx search and that the ":" character might have a special meaning. I do not know how to fix this. Can someone help me get rid of this stinkin' colon?
Slightly related...
I couldn't get these answers to work to replace all ":" in a string for the url encoded character %3a and modified this answer by'xdazz' to work: Javascript: Replace colon and comma characters to get...
str = str.replace(/:\s*/g, "%3a");
In your case it would be
str = str.replace(/:\s*/g, ".");
If you wanted to replace all colons with periods on a longer string.
Hope this helps somebody else.
The replace function returns a new string with the replacements made.
Javascript strings are immutable—it cannot modify the original string.
You need to write html = html.replace(":", ".");
I think c++ is the only high level language where strings are mutable. This means that replace cannot modify the string it operates on and so must return a new string instead.
Try the following instead
var element = jQuery('.checkout td h4');
element.html(element.html().replace(":", "."));
Or, perhaps more correctly (since you may have multiple elements).
jQuery('.checkout td h4').html(
function (index, oldHtml) {
return oldHtml.replace(":", ".");
}
);

Categories