Searching a string for the occurance of another string is a very common need. For example, does an email address contain the "@" symbol?
You can do this various ways using the String object.
g – Global match – Whether to test the regular expression against all possible matches in a string, or only against the first.
i – Ignore case
m – Multi-line; ^ and $ work over all lines, not just the input string (in other words, it will be sensitive to \n characters).
y – Sticky
<script type="text/javascript"> var email = "larry@stooges.com"; var pos = email.indexOf("@"); //pos=5 (zero-based) </script>
<script type="text/javascript"> var email = "larry@stooges.com"; var posArray = email.match(/@/g); //[0]="@", [1]="@" </script>
match()
will return an array of matched strings if the global flag is used (in this example, it is the g following the last slash).
<script type="text/javascript"> var email = "larry@stooges.com"; var pos = email.search(/@/); //pos=5 (zero-based) </script>
This is similar to indexOf(), except a Regular Expression is used to find the "sought" string. .search()
returns a -1 if the string is not found.
When specifying the start and end values, think of them as the spaces between the characters. If we want just the word “ipsum” specify the start and end values that wrap the word — 6 and 11.
↓ ↓
Lorem ipsum dolor sit amet
012345678901234567890123456
var myString = String("Lorum ipsum dolor sit amet"); var ipsum = myString.substring(6, 11);
This is similar to the previous example, but instead of an end (index) value, you specify the length that you want extracted out of the string. So, if you just want “ipsum” you would specify:
var myString = String("Lorum ipsum dolor sit amet"); var ipsum = myString.substr(6, 5);
It is possible to bypass the String object and go straight to RegExp. This example will find a query parameter in a URL.
function getParameterByName(name) { var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search); return match && decodeURIComponent(match[1].replace(/\+/g, ' ')); }
The Regular Expressions page contains more information about the syntax of RegEx.
Let's say you need to replace one string with another. You could use the String object's .replace()
method but you will need to write a RegEx statment to use it. An alternate way is to create the following custom function that uses plain text arguments, so it is a bit easier to use.
String.prototype.replaceAll = function(str1, str2, ignore) { //str1 = original string, str2 = replacement value, ignore = case //'cheese corn'.replaceAll('cheese', 'caramel') will become 'caramel corn' return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2); };