![](/img/trans.png)
[英]Is it possible to match half of a string using regex or use half of a matched group?
[英]regex to match first half of any string?
我發現在沒有可變量詞的情況下很難做到
我希望能夠做類似的事情
var halfStrLength = string.length /2
string = string.replace(/.(?=.{halfStrLength})/g, '*')
// replaces all but the last half of string with *
考慮改用str.slice(beginIndex[, endIndex])
。 它返回一個新字符串。
您可能想向下或向上舍入halfStrLength,因為您不想嘗試將字符串以小數點半分割。
您可以這樣創建新的RegExp:
var times = string.length / 2;
var regexp = new RegExp('(.{'+times+'})');
string = string.replace(regexp,'*');
用
*
替換字符串的最后一半以外的所有字符
只需使用String.substr()
和String.padStart()
(Ecmascript 6)函數:
var s = 'halfStrLength', half = s.substr(s.length / 2).padStart(s.length, '*'); console.log(half);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.