/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] Trap For Single Quotes (Another Reg Exp Issue)..

Boy…

This has been my last four posts :rolleyes:… I guess over time I’ll get better with regular expressions.

My issue is that I’m trying to catch single quotes in a form field and replace it with something else. I think I’m close, but I know (as always) my reg exp is a little off…

Here’s what I have:

[CODE]
function replacecomma(){

var fields=document.user_form.elements;
var target_pattern;

var main_fields=new Array();

var i=0;

while(i<fields.length){

if (fields[i].name==”text_field”)
{main_fields.push(fields[i]); i++;}
}

for (var i=0; i<main_fields.length; i++){

var user_entry=main_fields[i].value;

for (var j=0; j<user_entry.length; j++){

if (user_entry.charAt(j)==”‘”){

[COLOR=”Blue”] var x=user_entry.charAt(j);
var pattern=eval(‘/^(((.)(‘{0})){‘+x+’}((.)(‘{0})))/g’);
user_entry=user_entry.replace(pattern, “somethingelse”);
main_fields[i].value=user_entry;[/COLOR]
}
}
}

}
[/CODE]

Can anyone get me closer to a solution?

to post a comment
JavaScript

9 Comments(s)

Copy linkTweet thisAlerts:
@justinbarneskinSep 02.2009 — Here's what I have, only need to tweek it a bit, perhaps not

One way to do it...
[code=html]
function rplc(s,o,n){ //(string,old,new)
while(s.indexOf(o)!=-1){s = s.replace(o,n);}
alert(s); // return s
}[/code]

Another way...
[code=html]
function ReplaceStuff(S,O,N){ var rx=new RegExp(O,'g'); S=S.replace(rx, N);
alert(S); // return S
}[/code]
Copy linkTweet thisAlerts:
@ChuckBauthorSep 02.2009 — Here's what I have, only need to tweek it a bit, perhaps not

One way to do it...
[code=html]
function rplc(s,o,n){ //(string,old,new)
while(s.indexOf(o)!=-1){s = s.replace(o,n);}
alert(s); // return s
}[/code]

Another way...
[code=html]
function ReplaceStuff(S,O,N){ var rx=new RegExp(O,'g'); S=S.replace(rx, N);
alert(S); // return S
}[/code]
[/QUOTE]


Appreciate the response,

your code reads "while the [COLOR="Blue"]part[/COLOR] in the string that I want to replace still exists, replace it with the [COLOR="Blue"]new part[/COLOR]"...

I already know how to replace the 'old' with the 'new'...I'm just trying to replace a single quote in a string with 'something'. So I need a reg exp that identifies a single quote and allows me to replace it's position with something else..
Copy linkTweet thisAlerts:
@justinbarneskinSep 02.2009 — Those codes will do it but, you only wish to make it happen on the first instance of a single quote?
Copy linkTweet thisAlerts:
@ChuckBauthorSep 02.2009 — Those codes will do it but, you only wish to make it happen on the first instance of a single quote?[/QUOTE]

On all instances of a single quote....

Apparently, when you submit a form to a database using PHP - in database applications - the single quote is used to denote the end of a field value.

So I have to find all instances and replace it with this string that I can't type here because every time I do it converts it to a single quote whenever I hit 'submit reply'....because this forum uses php too....

I just need a regular expression to find a single quote...(I should be able to handle it from there)...
Copy linkTweet thisAlerts:
@pe51Sep 02.2009 — So from all HTML fields you have put those named as 'text_field' into an array called main_fields. You search all 'text_fields' in main_fields (using var i) for the single quote character (') (using var j). Then you want to replace them all by something else, say ("somethingelse").

The var user_entry is a string, containing all user input characters. You used the string.replace() method, but not quite as it should be used. It works much easier than you think.

In string.replace( regexp, replacement_string ) regexp is a regular expression, showing (only) what should be replaced. For instance, you can do this:

[CODE]
var ms = "my original string";
var pattern1 = /original/;
// instead of pattern in the line below you can also write the expression itself: /original/
var ms1 = ms.replace( pattern1, "our" );
ms1; // -> "ourstring";
// when you use the 'g' flag behind the end slash of the regexp (you just write the letter g behind it), not only the first, but all matches are found:
var pattern2 = /in/g; // finds all "in"s;
var ms2 = ms.replace( pattern2, "IN"); // "my origINal strINg"
[/CODE]


This way you don't even need the for loop with var j, the < if user_entry.charAt(j)) > statement, and the < var x=user_entry.charAt(j) > declaration. Because string.replace searches & replaces the whole string itself. And if you define the var pattern, you do not need to use an eval() function, a regular expression is evaluated without. In Javascript you quite rarely use eval() - it does much more than you want, so it is often called 'evil'.

A regular expression in string.replace() shows all that is to be replaced, so you also do not need the lengthy pattern you used. All that needs to be in the pattern is the one & only character you want to replace.

So simply /'/ is the pattern you need to replace (only) the first found single quote. If you want to find & replace more or all single quotes in a textstring, you need to write the letter g behind the endslash of the regular expression: it then looks like < /'/g > If you do this, a global search (& replace) will be done - all over the string. If you use this 'g flag' in a string.replace() method, it replaces all matches.

An example:

[CODE]
var mystring = "there was a so called 'party' at angela's house";
var re1 = mystring.match(/'/);
mystring1 = mystring.replace( re1,'"');
mystring1; // -> "there was a so called "party' at angela's house";
[/CODE]


As you see, without the 'g' flag in re1 only the first single quote is replaced.

[CODE]
var mystring = "there was a so called 'party' at angela's house";
var re2 = /'/g;
mystring2 = mystring.replace( re2,'"');
mystring2; // -> "there was a so called "party" at angela"s house"
[/CODE]


As you see, using the g flag in re2 all 3 single quotes are replaced. The whole string is searched over & replaced, also < angela's > has been changed into < angela"s >. Maybe you don't want that in your own user_input. In that case we have to look at the regexp one more time:

[CODE]
var mystring = "there was a so called 'party' at angela's house";
var re3 = /B'|'B/g;
mystring3 = mystring.replace( re3,'"');
mystring3; // -> "there was a so called "party" at angela's house"
[/CODE]


Now only the single quotes at the beginning and end of words are replaced. I will explain the new regular expression re3:

< | > means 'or' in a regular expression in javascript;

< b > (lowercase) in regexps means: 'word boundary' = beginning or end of words, or beginning or end of the whole string. But in re3 the capital B is used: and < B > in regexps means: 'NOT a word boundary' - it matches non-word characters, all that is not (A-Z, a-z or 0-9). For instance, B matches a space. This B is what I used in re3, because we only want single quotes with a space before or after it changed.

< 'B > (the single quote plus slash ? means: a single quote before a non-word character or just before the end of the string

< /'B/g > finds (single quotes before spaces) in mystring;

< /B'/g > finds (single quotes after spaces) in mystring;

And the combination < /'B|B'/g > finds & changes all single quotes that are before or after a space in mystring, so the single quote inside < angela's > is not touched.

Now we know enough to rewrite the loop part in your code:

[CODE]
for (var i=0; i<main_fields.length; i++){
var user_entry = main_fields[i].value;
// you can use one of the 2 lines below in your replace method:
var pattern1 = /'/g; // with this pattern all single quotes are found;
var pattern2 = /'B|B'/g; // only single quotes before and after a space are found;
user_entry = user_entry.replace( pattern1, "somethingelse" );
main_fields[i].value = user_entry;
}
[/CODE]


Having another look at it, I think you can even omit you var user_entry:

[CODE]
for (var i=0; i<main_fields.length; i++){
// you can use one of the 2 lines below in your replace method:
var pattern1 = /'/g; // with this pattern all single quotes are found;
var pattern2 = /'B|B'/g; // only single quotes before and after a space are found;
main_fields[i].value = main_fields[i].value.replace( pattern1, "somethingelse" );
}
[/CODE]


If you want, you can make regular expressions that make exceptions for other single quotes in your text.

As far as I can see, this should work for you, ask if you want to know more.

Peter.
Copy linkTweet thisAlerts:
@ChuckBauthorSep 02.2009 — Really appreciate everything...now for a couple of things...

I understand your approach. You are saying just get the value of the input field where if it displays a specific pattern I don't want (in this case single quotes), then that pattern is replaced and there's no need to loop through it to see if the single quote exists.



And the combination < /'B|B'/g > finds & changes all single quotes that are before or after a space in mystring, so the single quote inside < angela's > is not touched.

[/quote]


This is the issue...[COLOR="Blue"]Angela is supposed to be touched[/COLOR]. With your approach it doesn't appear that I'm looking out for the single quotes that may appear in other instances - like if it has an alpha, alphanumeric, symbol, space..etc in front or after it. You only look to see if a single quote is defined by the spacing between it and the next character. That's why [COLOR="Blue"]angela's[/COLOR] isn't touched. And if you do code for symbols, alpha, and alphanumeric chars in front/behind the single quote, then that means that you need to include the possibility of another single quote that may appear in front/behind, which means that it's a double quote.

So my [B]updated[/B] approach was to [B]1.[/B] get the value of the field, [B]2.[/B] loop through each character in the field, [B]3.[/B] test to see if one of those characters is indeed a single quote, [B]4.[/B] if it is, get the position, and compare the single quote character and it's position to the appropriate reg exp that looks out for the patterns mentioned above, [B]5.[/B] if it does match the reg exp that looks for the patterns above, simply use /'+x+'/ to replace the single quote with that "something" (where x is the single quote character at it's position in the string).

Here's my updated version of the code:

[CODE]
function replacecomma(){

var fields=document.user_form.elements;
var target_pattern;

var main_fields=new Array();


for (var i=0; i<fields.length; i++){

if (fields[i].name=="text_field")
{main_fields.push(fields[i]);}
}



for (var i=0; i<main_fields.length; i++){

var user_entry=main_fields[i].value;

for (var j=0; j<user_entry.length; j++){

if (user_entry.charAt(j)=="'"){

var x=user_entry.charAt(j);
[COLOR="Blue"]var pattern=eval('/^((.)+(s)*)(('){0}){'+x+'}(('){0}))((s)*(.)+)$/');[/COLOR]


if(user_entry.match(pattern)!=null)
{
user_entry=user_entry.replace(RegExp(x,"g"), "something");
main_fields[i].value="";
main_fields[i].value=user_entry;
}
}
}
}


}
[/CODE]


And as always, my reg exp doesn't work...
Copy linkTweet thisAlerts:
@pe51Sep 02.2009 — Really appreciate everything...now for a couple of things...

I understand your approach. You are saying just get the value of the input field where if it displays a specific pattern I don't want (in this case single quotes), then that pattern is replaced and there's no need to loop through it to see if the single quote exists.



This is the issue...[COLOR="Blue"]Angela is supposed to be touched[/COLOR]. With your approach it doesn't appear that I'm looking out for the single quotes that may appear in other instances - like if it has an alpha, alphanumeric, symbol, space..etc in front or after it. You only look to see if a single quote is defined by the spacing between it and the next character. That's why [COLOR="Blue"]angela's[/COLOR] isn't touched. And if you do code for symbols, alpha, and alphanumeric chars in front/behind the single quote, then that means that you need to exclude the possibility of another single quote that may appear in front/behind, which means that it's a double quote.
[/QUOTE]

Well, if < angela's > single quote has to be touched, then you should use pattern 1 (= change all single quotes) instead of pattern2 (change only single quotes before & after spaces). That's why I made 2 pattern variables, so you could choose one of two. Maybe you overlooked this?

[CODE]
for (var i=0; i<main_fields.length; i++){
// you can use one of the 2 lines below in your replace method:
var pattern1 = /'/g; // with this pattern all single quotes are found;
var pattern2 = /'B|B'/g; // only single quotes before and after a space are found;
main_fields[i].value = main_fields[i].value.replace( pattern1, "somethingelse" );
}
[/CODE]


In order to find & replace all single quotes (including angela's), you can change this part into:

[CODE]
for (var i=0; i<main_fields.length; i++){
var pattern1 = /'/g; // with this pattern all single quotes are found;
main_fields[i].value = main_fields[i].value.replace( pattern1, "somethingelse" );
}
[/CODE]


Or did I miss another point?

Peter
Copy linkTweet thisAlerts:
@ChuckBauthorSep 03.2009 — 

Or did I miss another point?

Peter[/QUOTE]


You did a great job explaining it. I did miss one of two patterns and it did work (/'/g). I originally thought that the the browser wouldn't recognize double vs. single quotes, but it did. Keeping things simple is definitely the best way..Thanks.?
Copy linkTweet thisAlerts:
@pe51Sep 03.2009 — Two single quotes look like a double quote, but javascript (and other languages) see it different. Their ASCII codes are 39 resp. 34, their unicodes u0027 resp. u0022, their HTML codes [& # 3 9 ;] (without spaces) resp. [ &quot; ].

Anyway, the string.search() method, the string.replace() method, regular expressions and the array.sort() method identify them by their character encoding. You can find out by playing around a bit in alerts or in a console, like this:

[CODE]
var single = "'";
var double = '"';

single.charCodeAt(0); // 39
double.charCodeAt(0); // 34

String.fromCharCode(39); // "'";
String.fromCharCode(34); // """;

single > double; // true;
/'/ > /"/; // true; = the same comparison, written in regular expression literals;

var myarray = [ single, double ];
myarray.sort(); // [""", "'"]; double quote at the beginning, it has the lowest character code;
[ /'/g, /"/g ].sort(); // [ /"/g, /'/g ]; regular expression literals are sorted the same way;
[/CODE]


and:

[CODE]
var twosingles = "''";
var twodoubles = '""';

String.fromCharCode(39, 39); // "''"; = the same string as var twosingles;
single + single; // "''"; evaluates to the same string as the line above;
twosingles === single + single; // true;
twodoubles === double + double; // true;
twosingles === double; // false;
[/CODE]


This is the way, I think, the string.search() method, the string.replace method and regular expressions look at single and double quotes.

In javascript codelines of course, 2 single quotes are an empty string, interchangable with 2 double quotes: '' = "";

[CODE]
var empty1 = '';
var empty2 = "";
empty1 == empty2; // true;
[/CODE]


Maybe you don't need this, but I could not resist posting it.
×

Success!

Help @ChuckB spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...