- This app highlights search text within a string. It renders HTML on the screen via a variable and manipulates that HTML based on a query, a regular expression and REGEX replace logic.
- Note: to open web links in a new window use: ctrl+click on link
- A regular expression is "A sequence of characters that forms a search pattern, mainly for use in pattern-matching with strings, or string matching, i.e. “find and replace”-like operations."
- Run
ng test
to run some simple Jasmin testson Karma. - Run
ng lint
to check syntax using TSLint. Note TSLint will be replaced with ESLint - Run
ng serve
for a dev server. - Navigate to
http://localhost:4200/
. The app will automatically reload if you change any of the source files.
- extract from
app.component.ts file
export class AppComponent {
private content: string;
public query: string;
public constructor() {
// tslint:disable-next-line: max-line-length
this.content = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent a quam ornare bibendum; ligula; a, rhoncus; ligula. Etiam; aliquet, justo; sollicitudin; imperdiet; luctus, nulla justo; sodales; mi, sit; amet; semper; nisl; velit; vel; massa. In; hac; habitasse; platea; dictumst';
}
// if no text in query then just return
public highlight(): string {
if (!this.query) {
return this.content;
}
/*The regular expression looks for all case insensitive occurrences of this.query.
Take the matches and wrap them in HTML tags with the CSS class name that we created.*/
return this.content.replace(new RegExp(this.query, 'gi'), match => {
return '<span class="highlightText">' + match + '</span>';
});
}
}
- text that matches what is being searched for is highlighted. The query is case-insensitive.
- Status: Working. Passes basic Jasmine tests
- To-Do: This could be used as a sand-box to try out other angular functionality. Regex could be expanded to search for numbers and highlight them in a different colour etc.
- N/A
- Repo created by ABateman, email: [email protected]