Friday, May 18, 2007

Javascript RegExp

- Example 1


var regex = /<title[^>]*>([\s\S]*?)<\/title>/i;
while(match = regex.exec(httpResp)){
if ('Login Page' == match[1]) {
...

"?" is important in the above regexp. By default it is greedy mode, with ?, it means the group will stop at the first encountered '<';

exec return ["<title>Login Page</title>", "Login Page"] since group () is used in regex which is useful to extract interested content.

-Example 2

html += ' <a href="javascript:showManyToMany (groupsForUser, \'' +
rowData.name.replace(/\'/g, "\\'").replace(/\"/g, "&.quot;") + '\');">Edit</a>';

In this case, single quote has to be escaped by javascript \\'; however Double quotes has to be escaped by html as &.quot; rather than \\", otherwise, "unterminated string literal" error occur. It looks like browser can understand \', but it doesn't
understand \".

- Example 3
cartName.replace(" ", "_"); will only replace first occurrence of space character. It should be cartName.replace(/\s/g, "_"). 1st parameter is regExp, rather than string, and /g means global search for all occurrences of a pattern. Note that the regular expression doesn't need to be quoted.

No comments: