I am currently developing an app which requires multiple special characters at the end of the string.
Some examples are:
etc.
I would like to replace all these as follows:
Can someone help me in doing this?
Thanks!
Use the String.prototype.replace() method.
var str = 'Your string';
var regex = 'Your regex';
str.replace(regex, 'replaced by this string');
Java version of code:
String myName ="5 ABCD898* + -";
char[] line = myName.toCharArray();
for(int i = line.length-1; i>=0; i--)
{
if (!((line[i] >= 'a' && line[i]<='z') || (line[i] >= 'A' && line[i]<='Z')||(line[i] >= '0' && line[i]<='9')))
{
line[i] = ' ';
}else{
break;}
}
myName=String.valueOf(line).trim()+"A";
System.out.println(myName);
other version of code
string line="5 * + -";
for(int i = line.size()-1; i>=0; i--)
{
if (!((line[i] >= 'a' && line[i]<='z') || (line[i] >= 'A' && line[i]<='Z')||(line[i] >= '0' && line[i]<='9')))
{
line[i] = '\0';
}else{
break;}
}
line+="A";
You can use String.prototype.replace()
with callback which will help you modify the string
const inputs = ['5*+-', '345-+', 'ABC+-++']; const results = inputs.map(s => { const specialChr = /[^A-Za-z0-9 ].*/g; const output = s.replace(specialChr, function (matched, index, original) { return matched + original.slice(0, index) + 'A'; }); return output; }); console.log(results);
Fastest for you, split
on first special char
and get the first
.
const clean = (str) => str.split(/\W/)[0]+"A"
const clean = (str) => str.split(/\W/)[0]+"A" const data = `5*+- to 5A 345-+ to 345A ABC+-++ to ABCA`.split("\n") data.forEach(line => console.log(clean(line)))
Depends what you mean by "special characters". I'd suggest a RegEx approach. Start off by looking at W3Schools
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.