/    Sign up×
Community /Pin to ProfileBookmark

Simple Regular Expression

I don’t know how to mix ‘s’ with regular literals.

What I would like to do is to be flexible on how many spaces there are after “My Foo”.

The first code works and testarray returns with something.

[CODE]
var test=”My Foo <span class=”subCounts”>((.*?))</span>”;
var testarray=document.body.innerHTML.match(new RegExp(test,’g’));
[/CODE]

The second code doesn’t work and testarray returns null.

[CODE]
var test=”My Foos*<span class=”subCounts”>((.*?))</span>”;
var testarray=document.body.innerHTML.match(new RegExp(test,’g’));
[/CODE]

So it tells me that I dunno how to use s*

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@Sterling_IsfineApr 27.2009 — 
So it tells me that I dunno how to use s*[/QUOTE]
In a string it must be escaped: s
Copy linkTweet thisAlerts:
@cybernikeauthorApr 27.2009 — Thanks, it works.

But, sometimes I just don't understand the logic of escape. I thought "s" was one entity that would be same as "n". Why would I not need to do "n", but "s" is necessary?
Copy linkTweet thisAlerts:
@ZeroKilledApr 27.2009 — yes, is necessary to double backslash the entity when is going to be used as regular expression. the reason is as follow. the main one is that you are constructing a regular expression using a string. when javascript read an escape char, it might replace the sequence with the equivalent, but when there is no equivalent javascript simply remove the escape char. those things happen before the string is sent as argument to RegExp. so for example a string "s" is parsed to "s" and then sent to RegExp.

now, don't be confused that you always have to include double escape. that only apply when you create a regular expression using a literal string in javascript. so, ISN'T the case when reading a string from a textbox or when creating literal regular expression (/[i]reg exp[/i]/).
×

Success!

Help @cybernike 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.16,
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,
)...