Re: Replacing string containing quotes
- From: Martin Honnen <mahotrash@xxxxxxxx>
- Date: Tue, 02 Aug 2005 13:38:30 +0200
Christian Perthen wrote:
I have a long string containing double and single quotes such as
"<a onclick="removeValue('Cuba')">Cuba</a>, <a onclick="removeValue('Canada')">Canada</a>, <a class=a_small onclick="removeValue('US')">US</a>"
How can I assigned it to a variable and then remove "<a onclick="removeValue('Cuba')">Cuba</a>" part from it?
Here is an example that might do what you want or that you at could adapt to do what you want:
var string = "<a onclick=\"removeValue('Cuba')\">Cuba</a>, <a onclick=\"removeValue('Canada')\">Canada</a>, <a class=a_small onclick=\"removeValue('US')\">US</a>";
function removeOnclick (input, value) {
var onclickPattern = new RegExp('<a[^>]+onclick="removeValue\\(\'' + value + '\'\\)">' + value + '</a>', 'g');
return input.replace(onclickPattern, '');
}
alert( removeOnclick(string, 'Cuba') + '\r\n\r\n' + removeOnclick(string, 'Canada') + '\r\n\r\n' + removeOnclick(string, 'US') + '\r\n\r\n' );
So you need to use the RegExp constructor and pass in a string with the regular expression pattern as you obviously want to have a different expression depending on a function parameter (e.g. 'Cuba' or 'US').
And constructing regular expression patterns from strings is a tedious task as you need to take care of both string escape as well as regular expression escape mechanism so you end up with stuff like
'<a[^>]+onclick="removeValue\\(\''
above which needs to escape the single quote in the string with \' and needs to escape the backslash with \\ to ensure in the regular expression the parenthesis ( occurs escaped as \(.
--
Martin Honnen --- MVP XML http://JavaScript.FAQTs.com/ .
- References:
- Replacing string containing quotes
- From: Christian Perthen
- Replacing string containing quotes
- Prev by Date: Replacing string containing quotes
- Next by Date: Re: Replacing QueryString Name-Value
- Previous by thread: Replacing string containing quotes
- Next by thread: Can we get Registry Values through Javascript/VbScript
- Index(es):
Relevant Pages
|