如何使用Javascript從下面的字符串中清除29%?從字符串中清除方式百分比
This is a long string which is 29% of the others.
我需要某種方法來消除所有比例,從而使代碼必須以該字符串工作太:
This is a long string which is 22% of the others.
如何使用Javascript從下面的字符串中清除29%?從字符串中清除方式百分比
This is a long string which is 29% of the others.
我需要某種方法來消除所有比例,從而使代碼必須以該字符串工作太:
This is a long string which is 22% of the others.
正則表達式匹配\d+%
一個或多個數字後跟一個%
。這隨後是一個可選的空間,這樣你就不會在一行中的兩個空格結束。
var s = "This is a long string which is 29% of the others.";
s = s.replace(/\d+% ?/g, "");
console.log(s);
// This is a long string which is of the others.
沒有在表達式的結束可選的空間,你最終
// This is a long string which is of the others.
//-------------------------------^^
這應該做的工作!
var s = 'This is a long string which is 29% of the others.';
s = s.replace(/[0-9]+%\s?/g, '');
alert(s);
我用所謂的正則表達式做到這一點。如果您想了解更多關於解決方案的信息,I'd recommend this website!
關閉!但它只能刪除%符號。我也需要刪除數字。所以從上面的字符串我也需要刪除29。 –
@Jonathan:如果你需要支持小數(例如「Blah blah 22.5%blah blah」),我相信正則表達式是'/ \ d +(?:\。\ d +)?%/ g'。 –
@Jonathan:我認爲你一定是錯誤地複製了Zanathiel的答案,對我很有用(我的小數正則表達式也適用於整數):http://jsbin.com/inarux注意Michael關於後面的空間的觀點,但是。 –
爲什麼不只是做
This is a long string which is <span id="pct">29%</span> of the others.
然後當你想這一些改變javascript只是使用:
var i = 22; //change this to what you want :)
document.getElementById("pct").innerHTML = i +"%";
承認這很可能,但OP不一定*在Web瀏覽器上執行此操作。 JavaScript被限制在網頁瀏覽器中的日子已經真正消失了(如果它們真的存在的話)。 –
@ T.J.Crowder:更可能的是,OP在瀏覽器中這樣做,但僅僅是出於與DOM無關的原因。 – rvighne
你可以使用正則表達式來替換後面跟着「%」的數字
var str = "This is a long string which is 29% of the others.";
var withoutPercentage = str.replace(/(\d+%)/, "");
不需要捕獲組。 –
同意你的意見。 –
你最好的選擇可能是經常性的。這個表達式將讓你的百分比:\d+%
。
所以這樣的事情應該做的伎倆:
var s='This is a long string which is 22% of the others.';
s= s.replace(/\d+%/g, 'REPLACE');
alert(s);
你提到處理的空白。下面是處理百分比內的空白和潛力小數點的解決方案:
s = s.replace(/(?)\d+(?:\.\d+)?%(?)/g, function(m, c0, c1) {
if (c0 === " " && c1 === " ") {
return " ";
}
return "";
});
這裏是如何工作的:
(?)
是捕獲在數字前面的空間,如果有一個捕獲組。如果沒有一個,它就什麼也沒有,因爲?
使空間可選。\d+
與前幾位數字匹配。(?:\.\d+)
匹配一個可選小數點後跟更多數字。 (這是不是捕獲集團,(?:xxx)
格式是沒有捕捉分組;在?
後更是令整個事情可選。)%
當然匹配%
。(?)
最後捕獲%
後面的空格,如果有的話;它也是可選的。String#replace
允許您提供將被調用的函數,而不僅僅是一個簡單的替換字符串。如果你也想處理像.25%
的東西,正則表達式修改了一下:
/(?)(?:(?:\d+\.\d+)|(?:\.\d+)|(?:\d+))%(?)/g
擊穿:
(?)
- 和以前一樣。(?:...|...|...)
- 一個替代,它將匹配給出的替代方案之一。我們給出的替代方案是:
(?:\d+\.\d+)
- 一個或多個數字後跟一個小數點後面跟一個或多個數字。(?:\.\d+)
- 一家領先的小數點後面跟着一個或多個數字(?:\d+)
- 只是一系列的數字%
- 匹配%
(?)
- 和以前一樣其餘的都是一樣的。
你在這裏幹什麼?我甚至都沒有看到你有答案! ;)+1 – RightSaidFred
反正我得到這個空間。 –