Home > database >  How to remove known portion from a text and get the arbitrary strings from it in js?
How to remove known portion from a text and get the arbitrary strings from it in js?

Time:07-02

I have a text format like this:

what is your favorite color from these?

Here color can be replaced with anything the user wants. For example food, juice, movie, book, etc. Now I want to remove the what is your favorite and from these? parts and only want the part that the user has inputted.

I know I can do slice twice to get that. Is there any other elegant solution? like regex?

edit: I am actually making a bot, so I can't use template literals. I need the text as it is and disregard the known portion from it.

Thank you.

CodePudding user response:

You could use a template literal syntax `` to do that.

Example:

var color = document.getElementById('user-input'); // just for the idea

what is your favorite ${color} from these?

And it will dynamically append the user input inside the string.

CodePudding user response:

Try this :

let defaultVal = 'color';
let str = `what is your favorite ${defaultVal} from these?`;

function getUpdatedVal() {
    const val = document.getElementById('val').value;
  if (val) {
    str = str.replace(defaultVal, val)
  }
  document.getElementById('result').innerText = str;
  defaultVal = val;
}
<input type="text" id="val" onchange="getUpdatedVal()"/>

<p id="result"></p>

CodePudding user response:

Capturing groups is one of the core mechanics in regular expressions. It allow you to get specific part of source text after matching. To solve your problem, you can use this pattern:

what is your favorite (\w ) from these\?

RegEx demo

After matching is success, target word will be in first capturing group.

  • Related