Let's say I get a string with special characters and I want to use filter/pipe to change it. Also the first letter of each word should be uppercase.
For example "@!₪ test stri&!ng₪"
will become "Test String"
.
How can that be done?
You can do with a pipe as follows,
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'specialPipe'
})
export class specialPipe implements PipeTransform {
transform(value: string): string {
let newVal = value.replace(/[^\w\s]/gi, '')
return newVal.charAt(1).toUpperCase() + newVal.slice(2);
}
}
use from the website: Regex101
For example: You want split or remove custome string: '@!₪ test stri&!ng₪' Type string in Test String
You can use a regular expression, along with replace
within your pipe to do so.
Firstly, use
str = str.replace(/[^\w\s]/gi, "")
This will remove all non-alpha characters
You can then use
str = str.replace(/\b\w/g, (str) => str.toUpperCase())
This will replace any letter character that is next to a word boundary (such as a space) with the upper case version.
You can then chain it together, like so:
let str = "@!₪ test stri&!ng₪"; str = str.replace(/[^\\w\\s]/gi, "") // Remove non word characters .trim() // Remove trailing and leadings spaces .replace(/\\b\\w/g, (s) => s.toUpperCase()) // Make the first letter of each word upper case console.log(str);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.