String functions in JavaScript by example
Apr 2, 2013 00:00 · 356 words · 2 minute read
You can capture the substring that has your desired pattern on a large string with expressions in JavaScript.
Some key point
\w
will match with any word character
\d
will match with any decimal digit
[]
Is used to match with set of characteristics
{0}
Is used to quantify a match i.e. {3} will match the first three characters.
()
Make capturing group
\
will escape special character
Match all with groups
var someText = "this is some <italic> important </italic> html text with some numbers such as 1, 3 and 6";
var expression = /<italic> (.*) <\/italic>/;
var result = expression.exec(someText);
alert("matched string : " + result[0]);
alert("capture string: " + result[1]);
(.*)
will capture anything that exists between
Check for the existence of a number
You can check if something exists in a string or not .
var numberExpression = /\d/;
var isContainNumber = numberExpression.test(someText);
alert("is the string contain number : " + isContainNumber);
“/\d/”
will look for any number on a string and the “test” method is check it against a string. Therefore it will return “true” as our string contains numbers.
Character Replace
You can replace a set of substrings in a string that matches with your desired pattern with regular expressions.
var spaceBetweenTwoWords = /(\w+) (\w+)/g;
var updatedString = someText.replace(spaceBetweenTwoWords, function (match, group1, group2) {
return group1.toUpperCase();
});
alert("replace each word with uppercase :" + updatedString);
(\w+)
is the first capture group that looking for any word with one or more character that followed by a white space with the second capture group. The pattern is looking for any word that has one or more character which surrounded by a space.
The “match” is showing all the matches with our criteria while “group1” and “group2” is contained only odd or even words. In the above example it will return “ THIS some
Download
Feel free to download the full source code of this example from my github.