[英]Javascript find and replace string within substring not using jquery
[英]jQuery - find and replace substring
假設我有這樣的字符串
'Hello, I am ***Groot*** today.'
'This is ***not*** my final form.'
'Test test ***123***'
我想在第一個和第二個星號之前添加一些新內容,使其看起來像
'Hello, I am FIRST***Groot***LAST today.'
'This is FIRST***not***LAST my final form.'
'Test test FIRST***123***LAST'
到目前為止,我設法做到了
var first = jQuery(this).html().indexOf("***");
var last = jQuery(this).html().lastIndexOf("***");
console.log( jQuery(this).html().substring(first, last+3) );
但是替換失敗了...那么近,到目前為止。
您可以很容易地使用regex ...這將適用於所有字符串。
JSFiddle (檢查js控制台)
var str = jQuery(this).text();
str = str.replace(/(\*{3}.*\*{3})/, "FIRST$1LAST");
console.log(str);
另外,您實際上並不需要創建jQuery對象來獲取文本,只需執行以下操作:
var str = this.innerText;
str = str.replace(/\*{3}.*\*{3}/, "FIRST$&LAST");
console.log(str);
我相信您的替換參數中正確的特殊替換字符應該是$&
而不是$1
只是出於可讀性和最佳實踐的考慮。
$&
對應於匹配的子字符串,而$1
使得RegExp對象中似乎有多個匹配項。
此處參考: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.