Basics
- Replacement var str="foobar-foobar" undefined str.replace('foo','bar') "barbar-foobar"
- Returns boolean for whether string is included var str = "Hello world, welcome to the universe."; str.includes("world"); true
Regular Expression (regex)
- replace() var re = /(\w+)\s(\w+)/igm; var str = 'John Smith'; var newstr = str.replace(re, '$2, $1'); console.log(newstr); // Smith, John Smith, John
- match() var re = /(\w+)\s(\w+)/igm; var str = 'John Smith foobar John Smith'; var newstr = str.match(re); console.log(newstr); // Smith, John VM29918:4 (2) ["John Smith", "foobar John"]
- test(): True or false var re = /(\w+)\s(\w+)/igm; var str = 'John Smith foobar John Smith'; var newstr = re.test(str) console.log(newstr); VM30242:4 true undefined var re = /(\w+)\s\n\n\n\n(\w+)/igm; var str = 'John Smith foobar John Smith'; var newstr = re.test(str) console.log(newstr); VM30250:4 false
Note that test() makes the regex pattern an object, unlike replace() and others. The key is to define the regex pattern separately.
- Modifiers
- i: Perform case-insensitive matching
- g: Perform global match (find all matches rather than stopping after the first match)
- m: Perform multiline matching
References: replace: https://www.w3schools.com/jsref/jsref_obj_regexp.asp https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace match: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/match https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String