How can I escape a ';' in Javascript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to write an algorithm where I replace characters like &, <, >, , ', " with their HTML entity counterpart(i.e. & would be replaced with &. This requires me to put a semi-colon in a string, which creates an error because Javascript thinks that I have ended the line. Here is my code:
str.charAt(i) = '&';
I thought that I could cancel it like so:
str.charAt(i) = '&amp\;';
but this creates an error.

The problem is that your assignment is invalid. You seem to be trying to mutate a string, which is impossible in JS since strings are immutable.
Instead you need to create a new string with the parts you want replaced with the new content.
var new_str = s.replace(/(?:(&)|(<)|(>)|(')|("))/g, function(s, g1,g2,g3,g4,g5) {
if (g1) return "&"
if (g2) return "<"
if (g3) return ">"
if (g4) return "&apos;"
if (g5) return """
});

Semi-colons inside string literals do not terminate statements in JavaScript.
ReferenceError: Invalid left-hand side in assignment
Your problem is that you are trying to assign a value to the return value of a function, which isn't allowed.
If you want to replace characters in a string, use the replace method.
In this case, you are trying to convert a string of text into a string of HTML and it is simpler to let the DOM do that for you:
var div_node = document.createElement('div');
var text_node = document.createTextNode(str);
div_node.appendChild(text_node);
var str_html = div_node.innerHTML;
Note that this won't replace all of the characters. Some don't need escaping all the time.

You don't need to escape semicolons inside strings. JavaScript doesn't think the line has ended in a string any more than it thinks the line ended inside for (var i = 0; ...).

The problem isn't an escaping issue. It's that you're attempting to assign a value to the static output of the String.charAt() method, which is not allowed.
Instead, try using the string replace method to replace your HTML entities with alternative values.
s = 'Hello & World';
s.replace(/\&/g, '&');

You can use a function to replace characters by their HTML entities:
function htmlEntities(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, '&apos;');
}
; don't need any replacement.

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);
}

Escape quotes on string javascript [duplicate]

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.

How to replace a string containing sqare brackets in javascript? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
how do you replace a string value with another in JavaScript ?
I have a string that contains a lot of this substring- Items[0]. How do I replace all of this to Items[1], taking into account that '0' is a dynamic value that I get from a variable.
I have used the replace method, and tried some 'RegExp' but couldn't do that. I think its because of those square brackets:
str.replace(new RegExp("Items[" + j + "]", "g"), "Items[" + (j - 1) +"]"));
Any help is appreciated. Thanks :)
You use new RegExp to create the regular expression. In the regex, you have to use \ to escape the [ because otherwise it has a special meaning. Since you're going to have to use a string to create the regex (since you need to include the value of your variable), you also have to escape the \ in the string, so we end up with two:
var variable = 0;
var rex = new RegExp("\\[" + variable + "]", "g");
var str = "This has Item[0] in more than one Item[0] place.";
var str = str.replace(rex, "Item[" + (variable + 1) + "]");
// If you want a dynamic replacement ^^^^^^^^^^^^^^^^^^^
// In this case, I used the value plus one.
console.log(str);
The "g" is a flag meaning "global" (throughout the string, not just the first occurrence).

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);
}

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