i'm trying to create a regex for replacing this kind of string :
(x bla bla bla)
Im looking for replace (x bla bla bla) by (x) then add new text
Here my jsfiddle : Jsfiddle
here my code :
var StartingLetter = 'x';
var NewText = 'Dadidu'
var regexTest = new RegExp('('+StartingLetter +')',"g");
$('.select_list option').text(function(i, oldText) {
//BlankText transform (x bla bla bla) by (x) ==> Doesnt work
var BlankText= oldText.replace(/\('+StartingLetter +'*?\)/, '('+StartingLetter +')')
//Then i replace with the new sentence (x) by (x Dadidu)
return oldText.replace(regexTest, StartingLetter +' '+ NewText);
});
You need to revamp the code as follows:
$(document).ready(function() {
var StartingLetter = 'x';
var NewText = 'Dadidu'
$('.select_list option').text(function(i, oldText) {
return oldText.replace(new RegExp(String.raw`\((${StartingLetter})[^()]*\)`,'g'), `($1 ${NewText})`)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://altair-html.tzdthemes.com/assets/js/common.min.js"></script>
<select class="select_list">
<option>Hello option A (x blabla bla)</option>
<option>Hello option B (x dididdidi)</option>
</select>
Here,
new RegExp(String.raw`\((${StartingLetter})[^()]*\)`,'g') declares a regex dynamically, String.raw help avoid doubling backslashes, g allows matching all non-overlapping occurrences in the string. Note the added [^()]* part, it matches zero or more chars other than round parentheses, and ${StartingLetter} is wrapped with capturing parentheses($1 ${NewText}) is the replacement pattern, $1 stands for the captured Group 1 value and ${NewText} is the word you want to append to the (x part.