-->

Welcome to our Coding with python Page!!! hier you find various code with PHP, Python, AI, Cyber, etc ... Electricity, Energy, Nuclear Power

Wednesday 26 June 2019

Is there a Javascript method that will achieve concatenation of nested parenthesis?

I am trying to create a string from input but formatted in a unique way.
Inputs will be single words: word1
The string will be empty until the first input comes then the string myString will be +(-word1).
For the second input: word2myString needs to now look like:
    +(-word1+(-word2))
For clarity, a third input: word3myString will now be:
    +(-word1+(-word2+(-word3)))
I believe this is going to require something a little more clever than normal string concatenation. I would prefer to not use a loop.

Is there a native Javascript (or potentially JQuery) function that can accomplish creating a string like this?

Here is what I have done
    var myString = '';

    function someFunction()
    { 
     ...

      var inputString = document.getElementById('my-input').value;
      myString = myString + "+(" + "-" + inputString + ")";
    }
However this is producing
    +(-word1)+(-word2)
This makes sense because the strings are just being concatenated in the function, what needs to happen rather is a sort of insertion. Is there a Javascript method that could make this insertion easier? Perhaps something like inserting the new string at the second to last space of the current string? However it's not an array so I don't know best practices here.
HERE IS THe SOLUTION
You look for the first closing parentesis and replace the value.
const insert = (s, v) => s ? s.replace(/(?=\))/, `+(-${v})`) : `+(-${v})`;

console.log(['word1', 'word2', 'word3'].reduce(insert, undefined));

No comments:

Post a Comment

Thanks for your comments

Rank

seo