簡體   English   中英

刪除字符串末尾的所有特殊字符

[英]Remove all special characters from the end of a string

我目前正在開發一個需要在字符串末尾有多個特殊字符的應用程序。

一些例子是:

  1. 5 * + -
  2. 345-+
  3. ABC+-++

等等

我想將所有這些替換如下:

  1. 5*+- 至 5A
  2. 345-+ 至 345A
  3. ABC+-++ 到 ABCA

有人可以幫我這樣做嗎?

謝謝!

使用 String.prototype.replace() 方法。

var str = 'Your string';
var regex = 'Your regex';
str.replace(regex, 'replaced by this string');

Java版本代碼:

    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);

其他版本的代碼

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";

您可以將String.prototype.replace()與回調一起使用,這將幫助您修改字符串

 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);

對您來說最快, split first special char並獲得第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)))

取決於您所說的“特殊字符”是什么意思。 我建議使用 RegEx 方法。 從查看W3Schools開始

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM