simplycoding
simplycoding

Reputation: 2967

Single JS function to replace multiple strings

I have the ability to include basic Javascript functions in a web-app (FormAssembly) and I need it to parse and do some string replacement. I don't know JS and have been struggling to figure out how to get the proper syntax and logic, so hopefully this makes sense.

An example of an allowed Javascript function in this app is: if(var=="banana"){"banana;"}else{""}

The input text var can be in the form of a few fruits, just as banana, bananagrape, or bananagrapekiwi. There are up to 5 values, and I know all the possible values. Basically I want to append a semicolon ; character to all the fruits so that the output text would be banana; or banana;grape;kiwi;

Here's what I've come up with. I'm not able to retrieve error message from this web app FormAssembly so I can't tell what's not working:

<script>
const parseFruit = (val) => {
    return val.replace(/banana/g,"banana;").replace(/kiwi/g,"kiwi;")
    }
</script>

Any help to get the proper syntax would be appreciated

Update: looks like the initial function is working for input parameters that don't have any spaces. How would I include spaces in the first parameter in the replace function?

<script>
const parseFruit = (val) => {
    return val.replace(/banana/g,"banana;").replace(/other fruit/g,"other fruit;")
    }
</script>

Upvotes: 0

Views: 91

Answers (1)

adiga
adiga

Reputation: 35202

You could create an alternation and replace the matches with an extra ;

$& gets the matched substring

const parseFruit = val => val.replace(/banana|kiwi|grape/g, "$&;")

console.log(parseFruit("bananagrapekiwi"))
console.log(parseFruit("bananakiwi"))

If you have an array of fruits, you could create a dynamic alternation by joining the array with | and RegExp constructor

const fruits = ["banana", "kiwi", "grape", "apple", "mango"],
      regex = new RegExp(fruits.join("|"), 'g');

const parseFruit = val => val.replace(regex, "$&;")

console.log(parseFruit("bananagrapekiwi"))
console.log(parseFruit("grapeapplemango"))
console.log(parseFruit("applebanana"))

Upvotes: 3

Related Questions