0

I have a text like

const a: string = 'I like orange, blue, black, pink, rose, yellow, white, black';

And a string

const b: string =['black', 'yellow'];

I want to replace in string a all black and yellow to violet, so it must look like on the screen

'I like orange, blue, violet, pink, rose, violet, white, violet'.

I know about function replace(), but have no idea how to pass b as argument...Could you please help me?

And if it is possible I would like to replace not with violet, but with input field, so i could type my own colors right in the text...Thank you!

1
  • See the documentation for that function Commented Jun 13, 2017 at 15:15

2 Answers 2

2

You could use a regular expression with the given array, joined by pipe as OR sign in the regular expression.

let a = 'I like orange, blue, black, pink, rose, yellow, white, black';
const b = ['black', 'yellow'];
   
a = a.replace(new RegExp(b.join('|'), 'g'), 'violet');

console.log(a);

With input

function change() {
    document.getElementById('output').innerHTML = 
        a.replace(new RegExp(b.join('|'), 'g'), document.getElementById('input').value);
}

let a = 'I like orange, blue, black, pink, rose, yellow, white, black';
const b = ['black', 'yellow'];
<input id="input" type="text" value="" onchange="change();" />
<div id="output"></div>

Sign up to request clarification or add additional context in comments.

6 Comments

@Arrow, she has not enough rep.
Do you know, it it possible to insert a input field, not the violet? Like in example link
Thank you again for you answer, but I meant a slightly different thing...So I would like to display text on screen, but instead of words from from array b, there must be inputs field, so I can type later different another colours and store it to array, so It will be array of my inputs. So like here, in this example link ...
i do not understand what you really want. maybe you ask a new question.
I guess there must be something like a.replace(new RegExp(b.join('|'), 'g'), <input/>); , so I could replace words with inputs
|
1

replace() doesn't accept arrays. But there is a work around. What you could do is loop over each word you would like to replace.

let a: string = 'I like orange, blue, black, pink, rose, yellow, white, black'

const b: string = ['black', 'yellow']

b.forEach(word => {
    a = a.replace(word, 'violet')
})

Also, const are immutable so if you want a variable you can modify make sure to use let.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.