Download PDF Javascript regular expressions 1st edition groner loiane manricks gabriel full chapter
JavaScript Regular Expressions 1st
Edition Groner Loiane Manricks Gabriel
Visit to download the full and correct content document: https://textbookfull.com/product/javascript-regular-expressions-1st-edition-groner-loia ne-manricks-gabriel/
More products digital (pdf, epub, mobi) instant download maybe you interests ...
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: May 2015
Production reference: 1250515
Published by Packt Publishing Ltd.
Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78328-225-8 www.packtpub.com
Credits
Authors
Loiane Groner
Gabriel Manricks
Reviewers
Andrea Barisone
Florian Bruniaux
Robert K Casto
Julio Freitas
Juri Strumpflohner
Commissioning Editor
Kunal Parikh
Acquisition Editor
Subho Gupta
Content Development Editor
Rohit Kumar Singh
Technical Editors
Bhupesh Kothari
Mrunmayee Patil
Copy Editor
Sonia Michelle Cheema
Project Coordinator
Mary Alex
Proofreaders
Stephen Copestake
Safis Editing
Indexer
Monica Ajmera Mehta
Graphics
Sheetal Aute
Production Coordinator
Conidon Miranda
Cover Work
Conidon Miranda
About the Authors
Loiane Groner has over 9 years of software development experience. In her university, she demonstrated a great deal of interest in IT. She worked as a teacher's assistant for 2.5 years for algorithms, data structures, and computing theory. She represented her university at the ACM International Collegiate Programming Contest – Brazilian Finals (South America Regionals), and she also worked as the student delegate of the SBC (Brazilian Computing Society) for 2 years. Loiane won a merit award in her senior year for being one of the top three students in her course. She had one of the highest GPAs in the computer science department, and also graduated with honors.
She has already worked at multinational companies, such as IBM. Her areas of expertise include Java SE and Java EE and also Sencha technologies (such as Ext JS and Sencha Touch). Nowadays, Loiane is working as a software development manager at a financial institution where she manages overseas solutions. She also works as an independent Sencha consultant and coach.
Loiane is also the author of Ext JS 4 First Look, Mastering Ext JS (first and second editions), Sencha Architect App Development, and Learning JavaScript Data Structure and Algorithms, all published by Packt Publishing.
She is passionate about Sencha and Java, and she is the CampinasJUG (Campinas Java Users Group) leader and an ESJUG (Espirito Santo Java Users Group) coordinator, both of which are Brazilian JUGs.
Loiane also contributes to the software development community through her blogs, which can be found at http://loianegroner.com (the English version) and http://loiane.com (the Portuguese-BR version), where she writes about IT careers, Ext JS, Sencha Touch, PhoneGap, Spring Framework, Java, and general development notes and also publishes screencasts.
If you want to keep in touch with her, you can find her on Facebook (https://www. facebook.com/loianegroner) and on Twitter (@loiane).
I would like to thank my parents for educating, guiding, and advising me through all these years and for helping me become a better human being and professional. A very special thank you to my husband for being patient and supportive and for giving me encouragement throughout.
I would like to thank Packt Publishing for this amazing opportunity to write books about the topics I really love! I'd like to thank all the people involved in the process of creating, reviewing, and publishing these books!
I would also like to thank the readers of this book and the other books I have written for their support and feedback. Your feedback is very valuable in helping me improve as an author and a professional. Thank you very much!
Gabriel Manricks is a full-stack software and web developer, and a writer. He is the CTO at CoinSimple and a staff writer at Nettuts+, where he enjoys learning as well as teaching others. He also freelances in the fields of web consulting, development, and writing.
About the Reviewers
Andrea Barisone works for a leading Italian IT company and has over 14 years of experience in information technology, working on corporate projects as a developer using different technologies.
He also has strong experience in ECM systems, and he has several J2EE certifications. He has a great ability in acquiring knowledge of new technologies and exploiting this knowledge by working with different environments and technologies.
Andrea has reviewed the following books:
• Agile Web Development with Rails 4, Pragmatic Bookshelf
• BPEL and Java Cookbook, Packt Publishing
• Learning Three.js: The JavaScript 3D Library for WebGL, Packt Publishing
• WebGL HotShots, Packt Publishing
• Automate with Grunt: The Build Tool for JavaScript, Pragmatic Bookshelf
• Andrea has also reviewed the video Building Applications with Ext JS, Packt Publishing
I would like to thank my parents, Renzo and Maria Carla; my beloved wife, Barbara; and my two wonderful little children, Gabriele and Aurora, for making my life as wonderful as they do.
Florian Bruniaux is a web development project manager at E-motors, France. He is passionate about new technologies, particularly about process optimization, database conception, and software development.
He has worked for various companies, such as Aylan, a French start-up; Oxylane; and EDF, where he worked on IT projects. This included working on server monitoring systems, cross-browser applications, multidevice app conceptions, and software development.
Robert K Casto was born and raised in Columbus, Ohio, where he graduated from the Ohio State University with a computer science degree in 1995. He has worked for companies, such as Concentus, Nationwide Financial Services, Amazon.com, Cornerstone Brands, PCMS, OXXO, Walgreens, Best Buy, and TuneWiki. He now lives in Cincinnati, Ohio, where he started SellersToolbox in 2011 to help companies sell their products on Amazon.com. He has spoken at SCOE (Sellers Conference for Online Entrepreneurs), and he volunteers for the Strange Loop conference in St Louis and the Boy Scouts with his son. He has reviewed a number of books and enjoys learning about software technologies, especially those that help automate or simplify processes.
I would like to express my gratitude to my family for their patience and understanding of my work and busy schedule. I also want to thank the people I work with at SellersToolbox, who have become indispensible to its success, and the many companies I have had the privilege to work with and assist. It is very gratifying to be able to help others and become a part of their pursuits.
Julio Freitas graduated in computer science, specializing in information systems and technology; he's been a developer of web applications since 2000. He worked as a developer and Unix systems administrator in projects related to grid computing using Java and PHP. He's also worked at the Center for Weather Forecasting and the Climate Studies/National Institute for Space Research (CPTEC/INPE), Brazil, for 5 years. He currently resides in England, where he started off working at a web systems company. Now, he's involved in creating his own start-up and is acting as a full-stack web developer in projects focused on API development and security and building applications for mobile devices using the MEAN stack and Ionic.
Juri Strumpflohner is a passionate developer who loves to code, follow the latest trends on web development, and share his findings with others. He has been working as a coding architect for an e-government company, where he is responsible for coaching developers, innovating, and making sure that software requirements meet the desired quality standards.
When he's not coding, Juri is either training or teaching Yoseikan Budo, a martial art form, where he currently owns a 2nd DAN black belt. Follow him on Twitter, where his handle is @juristr, or visit his blog at http://juristr.com to catch up with him.
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Preface
Regular expressions are patterns or templates, which allow you to define a set of rules in a natural yet vague way, giving you the ability to match and validate text. They have, more or less, been implemented in nearly every modern programming language.
When working with any type of textual input, you don't always know what the value will be, but you can usually assume (or even demand) the format you are going to receive into your application. These types of situations are exactly when you would create a regular expression to extract and manipulate this input.
In this book, you will learn the basics to get started with a regular expression in JavaScript. We will start with the basics, passing through some special patterns and then, dive into two examples. The first one is validating a web form, and the second one is a very complex pattern to extract information from a log file. For all the examples, we will use a step-by-step approach, which will make it easier to learn and assimilate all the knowledge we've gained from this book.
What this book covers
Chapter 1, Getting Started with Regex, presents an introduction about regular expressions in JavaScript. It also shows how to develop the program that will be used to test the regular expressions used in the first three chapters.
Chapter 2, The Basics, covers the main features of regular expressions in JavaScript, which are vague matchers, multipliers, and ranges.
Chapter 3, Special Characters, dives into the special characters patterns of Regex. It covers defining boundaries for a Regex, defining nongreedy quantifiers, and defining Regex with groups.
Preface
Chapter 4, Regex in Practice, demonstrates how to develop a web form and validate all its fields using regular expressions functionalities learned since the first chapter.
Chapter 5, Node.js and Regex, explains step by step how to create a simple application using Node.JS to read and parse an Apache log file using Regex. It also demonstrates how to display the information from the log file into a friendly web page to the user.
Appendix, JavaScript Regex Cheat Sheet, presents a summary of the patterns used in regular expressions in JavaScript along with their descriptions, and a list of useful methods to test and create regular expressions.
What you need for this book
To develop the source code presented in this book, you will need any text editor of your preference and a browser (such as Chrome or Firefox).
For Chapter 5, Node.js and Regex, you will also need to install Node.js in your computer. All the required steps are described in the chapter itself.
Who this book is for
This book is ideal for JavaScript developers who work with any type of user entry data. The book is designed for JavaScript programmers who possess basic to intermediate skills in JavaScript regular expressions, and want to learn about these for the first time or sharpen their skills to become experts.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Now, let's take a look at some of these helper functions, starting with err and clearResultsAndErrors."
A block of code is set as follows:
123-123-1234 (123)-123-1234
1231231234
Any command-line input or output is written as follows:
npm install http-server –g
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "The following image exemplifies the match of the regular expression when given a Text input."
Warnings or important notes appear in a box like this.
Preface
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files from your account at http://www. packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/ diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/ sites/default/files/downloads/1234OT_ColorImages.pdf
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub. com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/ content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at copyright@packtpub.com with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com, and we will do our best to address the problem.
Getting Started with Regex
Regular expressions are special kinds of tools used to represent patterns syntactically. When working with any type of textual input, you don't always know what the value will be, but you can usually assume (or even demand) the format you are going to receive into your application. These types of situations arise when you create a regular expression to extract and manipulate this input.
Consequently, to match a specific pattern requires a very mechanical syntax, since a change in even a single character or two can vastly change the behavior of a regular expression and, as a result, the final outcome as well.
Regular expressions by themselves (or Regex, for short) are not specific to any single programming language and you can definitely use them in nearly all the modern languages straight out of the box. However, different languages have implemented Regex with different feature sets and options; in this book, we will be taking a look at Regex through JavaScript, and its specific implementation and functions.
It's all about patterns
Regular expressions are strings that describe a pattern using a specialized syntax of characters, and throughout this book, we will be learning about these different characters and codes that are used to match and manipulate different pieces of data in a vague sort of manner. Now, before we can attempt to create a regular expression, we need to be able to spot and describe these patterns (in English). Let's take a look at a few different and common examples and later on in the book, when we have a stronger grasp on the syntax, we will see how to represent these patterns in code.
Analyzing a phone number
Let's begin with something simple, and take a look at a single phone number:
123-123-1234
We can describe this pattern as being three digits, a dash, then another three numbers, followed by a second dash, and finally four more numbers. It is pretty simple to do; we look at a string and describe how it is made up, and the preceding description will work perfectly if all your numbers follow the given pattern. Now, let's say, we add the following three phone numbers to this set:
123-123-1234
(123)-123-1234
1231231234
These are all valid phone numbers, and in your application, you probably want to be able to match all of them, giving the user the flexibility to write in whichever manner they feel most comfortable. So, let's have another go at our pattern. Now, I would say we have three numbers, optionally inside brackets, then an optional dash, another three numbers, followed by another optional dash, and finally four more digits. In this example, the only parts that are mandatory are the ten digits: the placing of dashes and brackets would completely be up to the user.
Notice also that we haven't put any constraints on the actual digits, and as a matter of fact, we don't even know what they will be, but we do know that they have to be numbers (as opposed to letters, for instance), so we've only placed this constraint:
Analyzing a simple log file
Sometimes, we might have a more specific constraint than just a digit or a letter; in other cases, we may want a specific word or at least a word from a specific group. In these cases (and mostly with all patterns), the more specific you can be, the better. Let's take the following example:
[info] – App Started
[warning] – Job Queue Full
[info] – Client Connected
[error] – Error Parsing Input
[info] – Application Exited Successfully
This is an example of some sort of log, of course, and we can simply say that each line is a single log message. However, this doesn't help us if we want to manipulate or extract the data more specifically. Another option would be to say that we have some kind of word in brackets, which refers to the log level, and then a message after the dash, which will consist of any number of words. Again, this isn't too specific, and our application may only know how to handle the three preceding log levels, so, you may want to ignore everything else or raise an error.
To best describe the preceding pattern, we would say that you have a word, which can either be info, a warning, or an error inside a pair of square brackets, followed by a dash and then some sort of sentence, which makes up the log message. This will allow us to capture the information from the log more accurately and make sure our system is ready to handle the data before we send it:
Analyzing an XML file
The last example I want to discuss is when your pattern relies on itself; a perfect example of this is with something like XML. In XML you may have the following markup:
We could just say that the pattern consists of a tag, some text, and a closing tag. This isn't really specific enough for it to be a valid XML, since the closing tag has to match the opening one. So, if we define the pattern again, we would say that it contains some text wrapped by an opening tag on the left-hand side and a matching closing tag on the right-hand side:
The last three examples were just used to get us into the Regex train of thought; these are just a few of the common types of patterns and constraints, which you can use in your own applications.
Now that we know what kind of patterns we can create, let's take a moment to discuss what we can do with them; this includes the actual features and functions JavaScript provides to allow us to use these patterns once they're made.
Regex in JavaScript
In JavaScript, regular expressions are implemented as their own type of object (such as the RegExp object). These objects store patterns and options and can then be used to test and manipulate strings.
To start playing with regular expressions, the easiest thing to do is to enable a JavaScript console and play around with the values. The easiest way to get a console is to open up a browser, such as Chrome, and then open the JavaScript console on any page (press the command + option + J on a Mac or Ctrl + Shift + J).
Let's start by creating a simple regular expression; we haven't yet gotten into the specifics of the different special characters involved, so for now, we will just create a regular expression that matches a word. For example, we will create a regular expression that matches hello.
The RegExp constructor
Regular expressions can be created in two different ways in JavaScript, similar to the ones used in strings. There is a more explicit definition, where you call the constructor function and pass it the pattern of your choice (and optionally any settings as well), and then, there is the literal definition, which is a shorthand for the same process. Here is an example of both (you can type this straight into the JavaScript console):
var rgx1 = new RegExp("hello");
var rgx2 = /hello/;
Both these variables are essentially the same, it's pretty much a personal preference as to which you would use. The only real difference is that with the constructor method you use a string to create an expression: therefore, you have to make sure to escape any special characters beforehand, so it gets through to the regular expression.
Besides a pattern, both forms of Regex constructors accept a second parameter, which is a string of flags. Flags are like settings or properties, which are applied on the entire expression and can therefore change the behavior of both the pattern and its methods.
Using pattern flags
The first flag I would like to cover is the ignore case or i flag. Standard patterns are case sensitive, but if you have a pattern that can be in either case, this is a good option to set, allowing you to specify only one case and have the modifier adjust this for you, keeping the pattern short and flexible.
The next flag is the multiline or m flag, and this makes JavaScript treat each line in the string as essentially the start of a new string. So, for example, you could say that a string must start with the letter a. Usually, JavaScript would test to see if the entire string starts with the letter a, but with the m flag, it will test this constraint against each line individually, so any of the lines can pass this test by starting with a.
The last flag is the global or g flag. Without this flag, the RegExp object only checks whether there is a match in the string, returning on the first one that's found; however, in some situations, you don't just want to know if the string matches, you may want to know about all the matches specifically. This is where the global flag comes in, and when it's used, it will modify the behavior of the different RegExp methods to allow you to get to all the matches, as opposed to only the first.
Getting Started with Regex
So, continuing from the preceding example, if we wanted to create the same pattern, but this time, with the case set as insensitive and using global flags, we would write something similar to this:
var rgx1 = new RegExp("hello", "gi");
var rgx2 = /hello/gi;
Using the rgx.test method
Now that we have created our regular expression objects, let's use its simplest function, the test function. The test method only returns true or false, based on whether a string matches a pattern or not. Here is an example of it in action:
> var rgx = /hello/; undefined
> rgx.test("hello"); true
> rgx.test("world"); false
> rgx.test("hello world"); true
As you can see, the first string matches and returns true, and the second string does not contain hello, so it returns false, and finally the last string matches the pattern In the pattern, we did not specify that the string had to only contain hello, so it matches the last string and returns true
Using the rgx.exec method
The next method on the RegExp object, is the exec function, which, instead of just checking whether the pattern matches the text or not, exec also returns some information about the match. For this example, let's create another regular expression, and get index for the start of the pattern;
> var rgx = /world/; undefined
> rgx.exec("world !!");
[ 'world' ]
> rgx.exec("hello world");
[ 'world' ]
> rgx.exec("hello"); null
Chapter 1
As you can see here, the result from the function contains the actual match as the first element (rgx.exec("world !!")[0];) and if you console.dir the results, you will see it also contains two properties: index and input, which store the starting index property and complete the input text, respectively. If there are no matches, the function will return null:
The string object and regular expressions
Besides these two methods on the RegExp object itself, there are a few methods on the string object that accept the RegExp object as a parameter.
Using the String.replace method
The most commonly used method is the replace method. As an example, let's say we have the foo foo string and we want to change it to qux qux. Using replace with a string would only switch the first occurrence, as shown here:
Getting Started with Regex
In order to replace all the occurrences, we need to supply a RegExp object that has the g flag, as shown here:
Using the String.search method
Next, if you just want to find the (zero-based) index of the first match in a string, you can use the search method:
> str = "hello world"; "hello world"
> str.search(/world/);
6
Using the String.match method
The last method I want to talk about right now is the match function. This function returns the same output as the exec function we saw earlier when there was no g flag (it includes the index and input properties), but returned a regular Array of all the matches when the g flag was set. Here is an example of this:
Another random document with no related content on Scribd:
The Project Gutenberg eBook of Chambers's Journal of Popular Literature, Science, and Art, fifth series, no. 139, vol. III, August 28, 1886
This ebook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this ebook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook.
Title: Chambers's Journal of Popular Literature, Science, and Art, fifth series, no. 139, vol. III, August 28, 1886
Author: Various
Release date: April 14, 2024 [eBook #73395]
Language: English
Original publication: Edinburgh: William and Robert Chambers, 1853
Credits: Susan Skinner, Eric Hutton and the Online Distributed Proofreading Team at https://www.pgdp.net (This file was produced from images generously made available by The Internet Archive) *** START OF THE PROJECT GUTENBERG EBOOK CHAMBERS'S JOURNAL OF POPULAR LITERATURE, SCIENCE, AND ART, FIFTH SERIES, NO. 139, VOL. III, AUGUST 28, 1886 ***
CHAMBERS’S JOURNAL
OF POPULAR LITERATURE, SCIENCE, AND ART
CONTENTS
OUR WAYS AND THEIRS. IN ALL SHADES. ‘TELEGRAPHED.’ A FRIEND OF THE FAMILY. THE MONTH: SCIENCE AND ARTS. CYCLING AS A HEALTH-PRODUCT. OCCASIONAL NOTES. PICCIOLA.
N . 139.—V . III. P 1½d. SATURDAY, AUGUST 28, 1886.
OUR WAYS AND THEIRS.
T do at Rome as the Romans do is sage advice, not always nor often followed by those of us who wander afield. Voluntarily placing ourselves among people whose ways and habits are different from our own, and whose principles of action are as sacred to them as ours are to us, we ‘fling our five fingers’ in the face of rules and regulations which are to them the very sign and substance of social decorum. Principles which are stricter than our own we call prejudices; and pooh-pooh as valueless those virtues in which we are wanting, while condemning as unpardonably immoral everything whatever which is of laxer fibre and looser holding than the corresponding circumstance at home. Thus, we fall foul of the southern nations for their want of straightforwardness, their sweet deceptive flatteries, their small short-sighted dishonesties; yet we count it but a little matter that they should be sober, abstemious, kind-hearted, and charitable; that they should not beat their children nor kick their wives to death; nor spend on one gross meal of beef and beer half the earnings of the week. We forget, too, that if we are ‘done’ in the vineyards and the orange groves, others are as much ‘done’ in the hop gardens and the hay-fields; and that: ‘Here is a stranger—come, let us rob him,’ is the rule of life all the world over We deride the costly political efforts made by young nations struggling to obtain a place in European councils; but we have not a word of praise for the patience with which the people bear their heavy burden of taxation, that their country may be great with the great, and strong with the strong. In short, we find more barren land than fertile, all the way from Dan to Beersheba; and, once across the silver streak, very few points, if any, attract our admiration, while fewer still compel our adhesion.
One of the most striking acts of unconformity lies in the charter of liberty given to our girls, compared with the close guard enforced among the bold wooers and jealous possessors of the fervid south.
An amount of freedom, which is both innocent and recognised here, is held as dangerous and improper there; but few English girls will submit to more personal restraint in Palermo or Madrid than that to which they have been accustomed in Cornwall or Cumberland. And indeed, they often launch out into strange license, and do things in foreign cities which they would not dare to do in their own native towns. They think they are not known; and what does it signify what people say of them?—the honour of the English name not counting. If you reason with them, and tell them that such and such things are ill thought of by the natives, they look at you blankly and answer: ‘What does it matter to us? Their ways are not ours, thank goodness! and we prefer our own. Besides, they must be very horrid people to think evil when there is none.’ Mothers and chaperons are no more sensitive, no more conformable, than their charges, and quite as resolute to reject any new view and trample under foot any rule of life to which they have not been accustomed. Tell one of them that, in a purely foreign hotel, the girl must not be let to sleep in another corridor—on another floor—or away from her own immediate vicinity, and she asks: ‘Why? My daughter is not a baby; she can take care of herself. And what harm should happen to her?’ Tell her that the girl must not wander unaccompanied about the passages, the gardens, the public rooms of the hotel, nor sit apart in corners of the salon talking in whispers with the men, nor lounge on the benches with one favoured individual alone—and she scouts all these precautions as foolish if not insulting. Say that it is not considered correct for the young lady to come to table-d’hôte by herself at any time of the meal it may suit her to appear—perhaps dashing into dinner in her hat, breathless, heated, excited—and again the advice is rejected. Her daughter has been accustomed to be mistress of her own time as well as actions, and lawn-tennis is a game which cannot be interrupted nor determined by one person only. She did just the same last year at Scarborough, and no one made unpleasant observations; so, why should she be under more control now? Yes, she did all these things at home, where they are compatible with ‘well-and-wise-walking.’ But in a foreign hotel, tenanted by men who respect young women only in proportion to the care that is taken of
them, they are not well nor wise; nay, more, they are looked on as criminal acts of neglect in those who have the guidance of things. Manners are special to countries as to classes, and are accepted as so much current coin, which passes here, but would not run out of the limits of the realm. Jermimer, down at Margate, giggles back to ’Arry, making lollipop eyes at her over the old boat, while sucking the knob of his sixpenny cane. From giggling and making lollipop eyes, the pair soon come to speech; from speech to association; from association to love-making in earnest, and mayhap to marriage. In any case, no harm is done; and Jermimer and ’Arry are as little out of the right course, judged from their own stand-point, when they make acquaintance in this primitive manner, as is Lady Clara Vere de Vere when she is whirled away in Lord Verisopht’s arms on a first introduction. The coin is good where it is minted. But Lady Clara Vere de Vere would be but base metal at Tangier and Tunis; and Jermimer is not understood, say at Palermo, when she comes there in force, trailing her Margate manners at her heels. Consequently, when three pretty girls alight at that fair city, and ‘carry on’ as if they were in ’appy ’Ampton, they naturally excite some attention, not of a flattering kind, among people to whom girlhood is at once brittle ware and a sacred deposit. A showy triad, dressed in the fluttering fashion dear to the tribe of Jermimer—bows here, ends there—colours which dazzle, and shapes not to be overlooked—they make themselves still more conspicuous by their millinery than nature has already made them by her gift of milkwhite skins and flaxen hair. They make themselves more conspicuous by their manners than by either millinery or colour. They care nothing for sight-seeing, and all for flirting, or what in their vernacular is ‘larking.’ Like their prototype giggling back to ’Arry over the old boat, they look back and laugh and beckon and nod to the young officers who follow them through the streets, thinking that here is sport made to their hand, and that to reject the roasted larks which fall from the sky would be a folly unworthy a rational human being. From looking they pass into speech; and, by aid of a dictionary and their fingers, make appointments and go off on expeditions, unchaperoned, with these young men, to whom they have no more clue than is given by their uniform and the number of their regiment. When warned by
experienced compatriots, they treat the warning as envy of their enjoyment. When advised by the handsome general who takes his own share of the cake, liberally, they treat his advice as jealousy of the younger men; and so, following their own course, they become the town’s talk, the shame of the English colony, the indignation of their hotel companions, and the standing marvel of the whole native population. They put, too, a stone in the hand of the reactionary and exclusive; and: ‘See to what your dangerous liberties lead your girls!’ is a reproach which no one can ward off. This is an instance of unconformity known to the writer of these lines as having taken place last winter in Palermo.
English and American girls flirt in a way which the fervid south neither permits nor understands. So far that fervid south is more real and more intense than we, who yet pride ourselves on both our sincerity and our depth. A painful little drama took place not long ago, founded on these cross lines of violated custom. Down on the Gulf of Naples a quite young girl, precocious in character and appearance and given up by her mother to the care of her maid, flirted with a young Italian as a foolish child would, given the chance, and only a venal servant to accept bribes for not looking after her. The young fellow took her seriously. When the trying moment came, she opened her large blue eyes and said with the candid air of a cherub: ‘I meant nothing but fun. I do not love you, and I am too young to marry.’ The youth shot himself as his commentary on her answer.
Again, no kind of warning as to the untrustworthiness of certain plausible scoundrels, known to be mere cacciatori or fortunehunters, will do any good to certain women determined to ruin themselves. A girl not long ago fell in love with a Sicilian scamp of handsome presence and desperate character. In vain her friends warned her of his reputation, and besought her to conquer her suicidal passion—in vain! in vain! She would not, and she did not; but, like the poor foolish moth, flew right up to the candle, and proved too fatally what the flame was like. She married; and then learnt what a torturer and a tyrant could do when put to it. Before the year was out she had to escape by stealth from a man who starved
her and beat her; who slept with a revolver under his pillow, with which he threatened her at dead of night—waking her from her sleep to terrify her into almost madness—and who made her regret too bitterly that she had not taken advice when it was given her, and believed in the truer knowledge of the more experienced. In health it is the same story. We, who go on a visit of a few weeks, know so much better what is good for us than the natives of the place, who have had the experience of a lifetime and the traditions of centuries to guide them! We laugh at their precautions, and refuse to be ‘coddled.’ Hence, we go straight into the jaws of danger, and then wonder that we are bitten. We hang over the malarial waters stagnating in the Colosseum, when we go there to ‘enthuse’ by moonlight. We lie on the rank grass in the Campagna, cooling our flushed faces on the earth which teems with the germs that slay and the emanations that destroy. We whip our blood to fever-heat by violent exertion under the burning sun, then get chilled to the marrow when the great orb sinks to darkness and the cold damps rise like malignant spirits from the tomb; and we think the inhabitants lazy because they take their exercise doucely, and effeminate because they avoid the half-hour of sundown as they would avoid a tiger crouching in the jungle. We eat and drink in feverish Italy and exciting Spain as we eat and drink in damp, depressing England; and we refuse to do at Rome as the Romans do, to the damage of our liver and the ruin of our nerves. We know best—are we not freeborn Britons?—and our flag of unconformity is the sign of our superiority We despise the religion of the countries we visit, and will not believe that the worshippers of the saints have more respect than have we ourselves for the faith into which they have been born and bred. A friend of our own carries this feeling to its last development, not being able to understand, nor to believe, that the old Greeks and Romans had any respect for Zeus or worship for Minerva. The grandeur and multiplicity of their temples, the magnificence and frequency of their processions, say nothing to him. Their ways are not his, and he cannot accept them as true for them if not for him. All people who have been abroad, and who respect the habits and feelings of those among whom they have placed themselves, know how painful it is to meet certain of their
countrymen and women in the churches during service. These nonconformists pay no more respect to the place than if it were a barn cleared out for a play-night. They walk about making comments in audible voices, and stepping over the obstructive feet of the kneeling worshippers as unconcernedly as if they were picking their way among so many bales of cotton and wool. Why should they not? When faith and habits clash, are not our own those which we must consider? At a funeral service in St Roch, when the nave was draped in black and occupied by the mourners gathered round the coffin, there came up the side aisle, arm-in-arm, a young Englishman and, perhaps, his bride, joyous, happy, talking, laughing. What to them, in the flush of their youthful bliss, was the sorrow of the widow, the grief of the children, the loss of a good man and a useful life? They were on one plane, and all these weeping mourners were on another; and their own was predominant.
In a smaller matter than this, we show the same want of conformity. We go to a theatre in full dress where the ladies of the place go in bonnets, and to the opera in ulsters and travel-worn hats where the élite are in their diamonds and plumes. But so it is all through. We are British, and may do as we like, not being slaves nor wearing wooden shoes like those others, and Britannia ruling the seas—a cross between Neptune and Minerva. We eat and drink and dress and flirt and live independent of the rules by which the people of the country are guided and checked. But if any one does not conform to our ways, he is anathematised, and we wonder how such bad taste is possible with a well-conditioned person! It is the stiff Anglo-Saxon neck, which, were it to bend, would not lose in power, but would gain in grace.
IN ALL SHADES.
CHAPTER XLII.
M was behind in the dining-room and bedrooms with Aunt Clemmy, helping to nurse and tend the sick and wounded as well as she could, in the midst of so much turmoil and danger. When she and Edward had been roused by the sudden glare of the burning cane-houses, reddening the horizon by Orange Grove, and casting weird and fitful shadows from all the mango-trees in front of their little tangled garden, she had been afraid to remain behind alone at Mulberry, and had preferred facing the maddened rioters by her husband’s side, to stopping by herself under such circumstances among the unfamiliar black servants in her own house. So they had ridden across hurriedly to the Dupuys’ together, especially as Marian was no less timid on Nora’s account than on her own; and when they reached the little garden gate that led in by the back path, she had slipped up alone, unperceived by the mob, while Edward went round openly to the front door and tried to appease the angry negroes.
The shouts and yells when she first arrived had proved indeed very frightening and distracting; but after a time, she could guess, from the comparative silence which ensued, that Edward had succeeded in gaining a hearing: and then she and Aunt Clemmy turned with fast beating hearts to look after the bleeding victims, one of whom at least they gave up from the first as quite dead beyond the reach of hope or recovery
Nora was naturally the first to come to. She had fainted only; and though, in the crush and press, she had been trampled upon and very roughly handled by the barefooted negroes, she had got off, thanks to their shoeless condition, with little worse than a few ugly cuts and bruises. They laid her tenderly on her own bed, and bathed her brows over and over again with Cologne water; till, after a few
minutes, she sat up again, pale and deathly to look at, but proud and haughty and defiant as ever, with her eyes burning very brightly, and an angry quiver playing unchecked about her bloodless lips.
‘Is he dead?’ she asked calmly—as calmly as if it were the most ordinary question on earth, but yet with a curious tone of suppressed emotion, that even in that terrible moment did not wholly escape Marian’s quick womanly observation.
‘Your father?’ Marian answered, in a low voice.—‘Dear, dear, you mustn’t excite yourself now. You must be quite quiet, perfectly quiet. You’re not well enough to stand any talking or excitement yet. You must wait to hear about it all, darling, until you’re a little better.’
Nora’s lip curled a trifle as she answered almost disdainfully: ‘I’m not going to lie here and let myself be made an invalid of, while those murderers are out yonder still on the piazza. Let me get up and see what has happened.—No; I didn’t mean papa, Marian; I know he’s dead; I saw him lying hacked all to pieces outside on the sofa. I meant Mr Noel. Have they killed him? Have they killed him? He’s a brave man. Have the wretches killed him?’
‘We think not,’ Marian answered dubiously. ‘He’s in the next room, and two of the servants are there taking care of him.’
Nora rose from the bed with a sudden bound, and stood, pale and white, all trembling before them. ‘What are you stopping here wasting your care upon me for, then?’ she asked half angrily. ‘You think not—think not, indeed! Is this a time to be thinking and hesitating! Why are you looking after women who go into fainting-fits, like fools, at the wrong moment? I’m ashamed of myself, almost, for giving way visibly before the wretches—for letting them see I was half afraid of them. But I wasn’t afraid of them for myself, though— not a bit of it, Marian: it was only for—for Mr Noel.’ She said it after a moment’s brief hesitation, but without the faintest touch of girlish timidity or ill-timed reserve. Then she swept queen-like past Marian and Aunt Clemmy, in her white dinner dress—the same dress that she had worn when she was Marian’s bridesmaid—and walked quickly but composedly, as if nothing had happened, into the next bedroom.
The two negresses had already taken off Harry’s coat and waistcoat, and laid him on the bed with his shirt front all saturated with blood, and his forehead still bleeding violently, in spite of their unskilful efforts to stanch it with a wet towel. When Nora entered, he was lying there, stretched out at full length, speechless and senseless, the blood even then oozing slowly, by intermittent gurgling throbs, from the open gash across his right temple. There was another deeper and even worse wound gurgling similarly upon his left elbow.
‘They should have been here,’ Nora cried; ‘Marian and Clemmy should have been here, instead of looking after me in yonder.—Is he dead, Nita, is he dead? Tell me!’
‘No, missy,’ the girl answered, passively handing her the soaked towel. ‘Him doan’t dead yet; but him dyin’, him dyin’. De blood comin’ out ob him, spurt, spurt, spurt, so him can’t lib long, not anyway. Him bledded to death already, I tinkin’, a’most.’
Nora looked at the white face, and a few tears began at last to form slowly in her brimming eyelids. But she brushed them away quickly, before they had time to trickle down her blanched cheek, for her proud West Indian blood was up now, as much as the negroes’ had been a few minutes earlier; and she twisted her handkerchief round a pocket pencil so as to form a hasty extemporised tourniquet, which she fastened bravely and resolutely with intuitive skill above the open wound on the left elbow. She had no idea that the little jets in which the blood spurted out so rhythmically were indicative of that most dangerous wound, a severed artery; but she felt instinctively, somehow, that this was the right thing to do, and she did it without flinching, as if she had been used to dealing familiarly with dangerous wounds for half her lifetime. Then she twisted the hasty instrument tightly round till the artery was securely stopped, and the little jets ceased entirely at each pulsation of the now feeble and weakened heart.
‘Run for the doctor, somebody!’ she cried eagerly; ‘run for the doctor, or he’ll die outright before we can get help for him!’
But Nita and Rose, on their knees beside the wounded man, only cowered closer to the bedside, and shook with terror as another cry
rose on a sudden from outside from the excited negroes. It was the cry they raised when they found Delgado was really struck dead before their very eyes by the visible and immediate judgment of the Almighty.
Nora looked down at them with profound contempt, and merely said, in her resolute, scornful voice: ‘What! afraid even of your own people? Why, I’m not afraid of them; I, who am a white woman, and whom they’d murder now and hack to pieces, as soon as they’d look at me, if once they could catch me, when their blood’s up!—Marian, Marian! you’re a white woman; will you come with me?’
Marian trembled a little—she wasn’t upheld through that terrible scene by the ingrained hereditary pride of a superior race before the blind wrath of the inferior, bequeathed to Nora by her slave-owning ancestors; but she answered with hardly a moment’s hesitation: ‘Yes, Nora. If you wish it, I’ll go with you.’
There is something in these conflicts of race with race which raises the women of the higher blood for the time being into something braver and stronger than women. In England, Marian would never have dared to go out alone in the face of such a raging tumultuous mob, even of white people; but in Trinidad, under the influence of that terrible excitement, she found heart to put on her hat once more, and step forth with Nora under the profound shade of the spreading mango-trees, now hardly lighted up at all at fitful intervals by the dying glow from the burnt-out embers of the smoking cane-houses. They went down groping their way by the garden path, and came out at last upon the main bridle-road at the foot of the garden. There Marian drew back Nora timidly with a hand placed in quick warning upon her white shoulder. ‘Stand aside, dear,’ she whispered at her ear, pulling her back hastily within the garden gate and under the dark shadow of the big star-apple tree. ‘They’re coming down— they’re coming down! I hear them, I hear them! O God, O God, I shouldn’t have come away! They’ve killed Edward! My darling, my darling! They’ve killed him—they’ve killed him!’
‘I wouldn’t stand aside for myself,’ Nora answered half aloud, her eyes flashing proudly even in the shadowy gloom of the garden. ‘But
to save Mr Noel’s life, to save his life, I’ll stand aside if you wish, Marian.’
As they drew back into the dark shadow, even Nora trembling and shivering a little at the tramp of so many naked feet, some of the negroes passed close beside them outside the fence on their way down from the piazza, where they had just been electrified into sudden quietness by the awful sight of Louis Delgado’s dead body. They were talking earnestly and low among themselves, not, as before, shrieking and yelling and gesticulating wildly, but conversing half below their breath in a solemn, mysterious, awe-struck fashion.
‘De Lard be praise for Mr Hawtorn!’ one of them said as he passed unseen close beside them. ‘Him de black man fren’. We got nobody like him. I no’ would hurt Mr Hawtorn, de blessed man, not for de life ob me.’
Marian’s heart beat fast within her, but she said never a word, and only pressed Nora’s hand, which she held convulsively within her own, harder and tighter than ever, in her mute suspense and agony.
Presently another group passed close by, and another voice said tremulously: ‘Louis Delgado dead—Louis Delgado dead! Mr Hawtorn is wonderful man for true! Who’d have tought it, me brudder, who’d have tought it?’
‘That’s Martin Luther,’ Nora cried almost aloud, unable any longer to restrain her curiosity. ‘I know him by his voice. He wouldn’t hurt me. —Martin, Martin! what’s that you’re saying? Has Mr Hawthorn shot Delgado?’ As she spoke, with a fierce anticipatory triumph in her voice, she stepped out from the shadow of the gate on to the main bridle-path, in her white dress and with her pale face, clearly visible under the faint moonlight.
Martin flung up his arms like one stabbed to the heart, and shouted wildly: ‘De missy, de missy! Dem done killed her on de piazza yonder, and her duppy comin’ now already to scare us and trouble us!’
Even in that moment of awe and alarm, Nora laughed a little laugh of haughty contempt for the strong, big-built, hulking negro’s
superstitious terror ‘Martin!’ she cried, darting after him quickly, as he ran away awe-struck, and catching him by the shoulder with her light but palpable human grasp, ‘don’t you know me? I’m no duppy. It’s me myself, Missy Nora, calling you. Here, feel my hand; you see I’m alive still; you see your people haven’t killed me yet, even if you’ve killed your poor old master.—Martin, tell me, what’s this you’re all saying about Mr Hawthorn having shot Delgado?’
Martin, shaking violently in every limb, turned round and reassured himself slowly that it was really Nora and not her ghost that stood bodily before him. ‘Ha, missy,’ he answered good-humouredly, showing his great row of big white teeth, though still quaking visibly with terror, ‘don’t you be ’fraid; we wouldn’t hurt you, not a man of us. But it doan’t Mr Hawtorn dat shot Delgado! It God Almighty! De Lard hab smitten him!’
‘What!’ Nora cried in surprise. ‘He fell dead! Apoplexy or something, I suppose. The old villain! he deserved it, Martin.—And Mr Hawthorn? How about Mr Hawthorn? Have they hurt him? Have they killed him?’
‘Mr Hawtorn up to de house, missy, an’ all de niggers pray de Lard for true him lib for ebber, de blessed creature.’
‘Why are you all coming away now, then?’ Nora asked anxiously. ‘Where are you going to?’
‘Mr Hawtorn send us home,’ Martin answered submissively; ‘an’ we all ’fraid, if we doan’t go straight when him tell us, we drop down dead wit Kora, Datan, an’ Abiram, an’ lyin’ Ananias, same like Delgado.’
‘Marian,’ Nora said decisively, ‘go back to your husband. You ought to be with him.—Martin, you come along with me, sir. Mr Noel’s dying. You’ve killed him, you people, as you’ve killed my father. I’ve got to go and fetch the doctor now to save him; and you’ve got to come with me and take care of me.’
‘Oh, darling,’ Marian interrupted nervously, ‘you mustn’t go alone amongst all these angry, excited negroes with nobody but him. Don’t, don’t; I’ll gladly go with you!’
‘Do as I tell you!’ Nora cried in a tone of authority, with a firm stamp of her petulant little foot. ‘You ought to be with him. You mustn’t leave him.—That’s right, dear.—Now, then, Martin!’
‘I ’fraid, missy.’
‘Afraid! Nonsense. You’re a pack of cowards. Am I afraid? and I’m a woman! You ought to be ashamed of yourself. Come along with me at once, and do as I tell you.’
The terrified negro yielded grudgingly, and crept after her in the true crouching African fashion, compelled against his will to follow implicitly the mere bidding of the stronger and more imperious nature.
They wound down the zigzag path together, under the gaunt shadows of the overhanging bamboo clumps, waving weirdly to and fro with the breeze in the feeble moonlight—the strong man slouching along timorously, shaking and starting with terror at every rustle of Nora’s dress against the bracken and the tree ferns; the slight girl erect and fearless, walking a pace or two in front of her faint-hearted escort with proud self-reliance, and never pausing for a single second to cast a cautious glance to right or left among the tangled brushwood. The lights were now burning dimly in all the neighbouring negro cottages; and far away down in the distance, the long rows of gas lamps at Port-of-Spain gleamed double with elongated oblique reflections in the calm water of the sleepy harbour
They had got half-way down the lonely gully without meeting or passing a single soul, when, at a turn of the road where the bridlepath swept aside to avoid a rainy-season torrent, a horse came quickly upon them from in front, and the rapid click of a cocked pistol warned Nora of approaching danger.
‘Who goes there?’ cried a sharp voice with a marked Scotch accent from the gloom before her. ‘Stop this minute, or I’ll fire at you, you nigger!’
With a thrill of delight, Nora recognised the longed-for voice—the very one she was seeking. It was Dr Macfarlane, from beyond the gully, roused, like half the island, by the red glare from the Orange