簡體   English   中英

Javascript:在特定位置替換字符串

[英]Javascript : replace string at specific position

我有一個像這樣的字符串:

var str = "Hello, it is a <test>12345</test> and it's fun";

我想將“ 12345”替換為“ ****”。

該腳本必須考慮到包含在和之間字符串永遠不相同的事實

您可以使用此正則表達式:

str = str.replace(/(<test>).*?(?=<\/test>)/, '$1*****');
//=> "Hello, it is a <test>*****</test> and it's fun"

如果您不希望超前,請在兩側使用捕獲組:

str = str.replace(/(<test>).*?(<\/test>)/, '$1*****$2');
//=> "Hello, it is a <test>*****</test> and it's fun"

如果數字不一定總是被包含在<test>標記之間,則這是解決相同問題的另一種方法。

var str = "Hello, it is a <test>12345</test> and it's fun";

var numberPattern = /(\<\w+\>)(\d+)(\<\/\w+\>)/gi;

str = str.replace(numberPattern, "$1****$3");

// str is now "Hello, it is a <test>****</test> and it's fun"

暫無
暫無

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

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