Reputation: 3465
I have a problem when trying to use the result of match function in one new match.
This is the code:
<html>
<body>
<script type="text/javascript">
p="somelongtextmelongtextmelongtextmelongtext";
f1 = p.match(/some/g);
document.write(f1);
f2 = f1.match(/om/g);
document.write(f2);
</script>
</body>
</html>
The output is the word "some" when it must be "om". I don't understand this behavior and I need the output of f1 in a more complex situation.
Thanks in advance.
Upvotes: 1
Views: 1147
Reputation: 82
the output is "some" because it is failing on the line: f2 = f1.match(/om/g); it never gets to writing f2.
f1 is an object variable, not a string. the object doesn't have a match method. replace the offfending line with this:
f2 = f1.toString().match(/om/g);
HTH
Upvotes: 0
Reputation: 7354
Are you sure that you pasted the exact same code that you're testing?
I ask because f1 = p.match(/some/g);
returns an array of matches, and the Array
object does not have a .match
method, so f1.match(/om/g);
should throw an error.
Anyways, the correct way to do this is:
p="somelongtextmelongtextmelongtextmelongtext";
f1 = p.match(/some/g);
if (f1) {
f2 = f1[0].match(/om/g);
console.log(f2);
}
Upvotes: 6