我想從字串中替換除數字字符以外的所有內容,但如果 出現在字串的開頭,則應忽略它。例如
1234 !@#$%^&*()_ =-;',.><:" becomes 1234
1234 becomes 1234
1234 becomes 1234
1234 !@#$%^&*()_ =-;',.><:" becomes 1234
1234 !@#$%^&*()_ =-;',.><:" becomes 1234
1234ABCabc !@#$%^&*()_ =-;',.><:" becomes 1234
1234ABCabc !@#$%^&*()_ =-;',.><:" becomes 1234
Aa1234ABCabc !@#$%^&*()_ =-;',.><:" becomes 1234
a 1234ABCabc !@#$%^&*()_ =-;',.><:" becomes 1234
1 1234ABCabc !@#$%^&*()_ =-;',.><:" becomes 11234
你能建議嗎?
uj5u.com熱心網友回復:
你可以試試:
str.replace(/((?<!^)\D)|(^[^ 0-9])/g, '');
這取代(什么都沒有):
- 任何不在字串開頭的非數字。
uj5u.com熱心網友回復:
這會從字串中提取數字,包括可選的前導
:
var tests = [
'1234 !@#$%^&*()_ =-;\',.><:"', // becomes 1234
' 1234', // becomes 1234
' 1234', // becomes 1234
' 1234 !@#$%^&*()_ =-;\',.><:"', // becomes 1234
' 1234 !@#$%^&*()_ =-;\',.><:"', // becomes 1234
' 1234ABCabc !@#$%^&*()_ =-;\',.><:"', // becomes 1234
'1234ABCabc !@#$%^&*()_ =-;\',.><:"', // becomes 1234
'Aa1234ABCabc !@#$%^&*()_ =-;\',.><:"', // becomes 1234
'a 1234ABCabc !@#$%^&*()_ =-;\',.><:"', // becomes 1234
'1 1234ABCabc !@#$%^&*()_ =-;\',.><:"' // becomes 11234
];
tests.forEach(str => {
console.log(str ' => ' str.replace(/^.*?(\ ?[0-9] ).*$/, '$1'));
});
輸出:
1234 !@#$%^&*()_ =-;',.><:" => 1234
VM1036:2 1234 => 1234
VM1036:2 1234 => 1234
2VM1036:2 1234 !@#$%^&*()_ =-;',.><:" => 1234
VM1036:2 1234ABCabc !@#$%^&*()_ =-;',.><:" => 1234
VM1036:2 1234ABCabc !@#$%^&*()_ =-;',.><:" => 1234
VM1036:2 Aa1234ABCabc !@#$%^&*()_ =-;',.><:" => 1234
VM1036:2 a 1234ABCabc !@#$%^&*()_ =-;',.><:" => 1234
VM1036:2 1 1234ABCabc !@#$%^&*()_ =-;',.><:" => 1
您描述的目標和最后一個示例相互矛盾。請更具體地說明您需要什么。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/506398.html