Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
7

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

Explorer ,
Feb 28, 2024 Feb 28, 2024

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]);
}

 

TOPICS
Bug , Scripting
733
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

Community Expert , Feb 28, 2024 Feb 28, 2024

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]);
...
Translate
Community Expert ,
Feb 28, 2024 Feb 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".

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Feb 28, 2024 Feb 28, 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.

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Feb 28, 2024 Feb 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")

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Feb 28, 2024 Feb 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);
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Feb 28, 2024 Feb 28, 2024

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

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Feb 28, 2024 Feb 28, 2024

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.

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Feb 28, 2024 Feb 28, 2024

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

 

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Feb 29, 2024 Feb 29, 2024

Both of those do exactly what I needed. Thank you! I'm an amateur and got stuck on the wrong path. I never thought to not use RegExp because that's how I taught myself.

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Feb 29, 2024 Feb 29, 2024

Ah! No problem—it is great to see you giving it a go on your own. Keep it up!

 

In this case the relevant issue is that you can join strings with +.

- Mark

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Feb 29, 2024 Feb 29, 2024

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

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Guide ,
Feb 29, 2024 Feb 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

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Feb 29, 2024 Feb 29, 2024
LATEST

Very nice, Marc!

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines