Skip to main content
Known Participant
February 28, 2024
Answered

Replace() function adding extra parenthesis to string values that have parenthesis.

  • February 28, 2024
  • 4 replies
  • 1518 views

I'm attempting to add text to string values in an array. Some of these strings have parenthesis around them and for some reason the replace() function is adding extra parenthesis around these.

So "apples" becomes "I like apples." but "(oranges)" becomes "(I like (oranges).)"

Why is this happening? Is there a better way to do this?

Here is my code:

var words = new Array();
words = ["apples", "(oranges)", "peaches", "(mangos)"];
for (i = 0; i < words.length; i++) {
    words[i] = words[i].replace(new RegExp(words[i], "g"), "I like " + words[i] + ".");
    alert(words[i]);
}

 

This topic has been closed for replies.
Correct answer m1b

That's not working either. Now I get "()I like ()oranges().()".

var words = "(oranges)";
words = words.replace(/\(|\)/g, "\($1\)");
words = words.replace(new RegExp(words, "g"), "I like " + words + ".");
alert(words);

But you're pointing me in the right direction. Guess I need to learn more about regular expressions.


I'm sure there is a reason that isn't obvious in your simplified example, but why not use this:

 

var words = ["apples", "(oranges)", "peaches", "(mangos)"];
for (i = 0; i < words.length; i++) {
    words[i] = words[i].replace(words[i], "I like " + words[i] + ".");
    alert(words[i]);
}

 

I mean, from your example we could do this:

var words = ["apples", "(oranges)", "peaches", "(mangos)"];
for (i = 0; i < words.length; i++) {
    words[i] = 'I like ' + words[i] + '.';
    $.writeln(words[i]);
}

 

If that can't be done in your case, can you please improve your example so we can understand what you really need to do?

- Mark

 

4 replies

Marc Autret
Legend
February 29, 2024

Hi all,

 

1. For those seeking a more generic solution, based on localize:

 

// METHOD 1 - Using localize()
// -----------------------------

const PATTERN = "I like %1."; // ← Specify your pattern using `%1` placeholder.
var words = [ "apples", "(oranges)", "peaches", "(mangos)" ];

const L = $.global.localize;
for( var i=words.length ; i-- ; words[i]=L(PATTERN, words[i]) );

// Display result:
alert( words.join('\r') );

 

2. For those seeking a faster, generic solution, bypassing the for loop:

 

// METHOD 2 - No loop.
// -----------------------------

const PATTERN = "I like %1."; // ← Specify your pattern using `%1` placeholder (once).
var words = [ "apples", "(oranges)", "peaches", "(mangos)" ];

const XSEP = '\x01';
var t = PATTERN.split('%1');
words = ( t[0] + words.join(t[1]+XSEP+t[0]) + t[1] ).split(XSEP);

// Display result:
alert( words.join('\r') );

 

Best,

Marc

m1b
Community Expert
Community Expert
March 1, 2024

Very nice, Marc!

Peter Kahrel
Community Expert
Community Expert
February 29, 2024

Mark is right. You're replacing literals, no need for regular expressions.

brian_p_dts
Community Expert
Community Expert
February 28, 2024

You are converting "(oranges)" into a regex. Before doing that, you would need to escape the parens if you want to find them: .replace(/(|\)/g,"\$1")

choschAuthor
Known Participant
February 28, 2024

Ok, that's all well and good. But your code to escape the parens removed them from the string. What if I want to keep the parens? My ultimate goal is for it say "I like (oranges)."

Here is how I'm using your code:

var words = "(oranges)";
words = words.replace(/\(|\)/g, "\$1");
words = words.replace(new RegExp(words, "g"), "I like " + words + ".");
alert(words);
brian_p_dts
Community Expert
Community Expert
February 28, 2024

Got the replace wrong. Should be... ("\($1\)")

Robert at ID-Tasker
Legend
February 28, 2024

Isn't it the correct behaviour?

 

You are using "(oranges)" as a searchValue - and as "()" are used for grouping - RegExp is looking for "oranges" - WITHOUT "()" and replaces word "oranges" with "I like " + "(oranges)" + "." - but as your words[i] is "(oranges)" - it leaves "()" intact and only replaces "oranges".

 

choschAuthor
Known Participant
February 29, 2024

It's not what I intended, for sure. Your explanation makes sense and tells me I need to learn more about how RegExp works.