Last active
May 11, 2018 18:50
-
-
Save bschwartz757/65dd3e0c5ab5773af36c54d728f349f2 to your computer and use it in GitHub Desktop.
String/RegExp search methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="placeholder"> | |
Output goes here | |
</div> | |
const string = 'there is a cow in a field'; | |
function print(result) { | |
console.log(result); | |
document.getElementById('placeholder') | |
.innerText = result; | |
} | |
//String.indexOf(); | |
//returns index of first matched char, or -1 | |
function stringIndex(subStr) { | |
var found = string.indexOf(subStr); | |
print(found); | |
} | |
//stringIndex('stuff'); | |
//String.search(); | |
//same behavior as indexOf(); | |
function searchString(subStr) { | |
var found = string.search(subStr); | |
print(found); | |
} | |
//searchString(' is a '); | |
//RegExp.test(); | |
//searches using regex, returns boolean | |
//similar to string.search(), except return is bool | |
function testString(re) { | |
console.log(re.source); | |
var found = re.test(string); | |
print(found); | |
} | |
//testString(/there/); | |
//RegExp.exec(); | |
//returns an array of info (search term, index, input) or null | |
function execString(re) { | |
console.log(re.source); | |
var found = re.exec(string); | |
print(found); | |
} | |
//execString(/cow/); | |
//String.match(); | |
//returns an array of info (search term, index, input) or null | |
//similar to RegExp.exec(); | |
function matchString(re) { | |
console.log(re.source); | |
var found = string.match(re); | |
print(found); | |
} | |
//matchString(/there is a/); | |
//String.replace(); | |
//Searches for substr, and replaces if found | |
//can search by RegExp, and replace using fn | |
//returns a new string, orig string unchanged | |
function replaceString(subStr, newStr) { | |
print(string.replace(subStr, newStr)); | |
} | |
//replaceString('is a cow', 'are cows'); | |
//String.replace(); | |
//Uses RegExp or string to split string into | |
//array of substrings | |
function splitString(separator) { | |
var stringArr = string.split(separator); | |
print(stringArr); | |
} | |
//splitString(' '); | |
function reverseString(separator, newSeparator) { | |
var stringArr = string.split(separator) | |
.reverse() | |
.join(newSeparator); | |
print(stringArr); | |
} | |
reverseString(' ', ' / '); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment