Take element from a string

Asked

Viewed 158 times

0

Supposing I did have:

<script>
 var string = "Hello [background]image.png[background] World!";
</script>

It would be possible to find the image that is inside the two [background], and save to another variable, for example?

2 answers

2


Ericki, has how and there are numerous ways to do this, below two examples of how this can be done:

var string = "Hello [background]image.png[background] World!";

//Pegando o valor com regex
found = /\[background\](.*?)\[background\]/g.exec(string);

if(found) {
  //console.log(found);
  var backgroundValue1 = found[1];
  console.log(backgroundValue1);
}

//Pegando o valor procurando pelos índices...
var firstIndex = string.indexOf("[background]");

if(firstIndex) {

  //Remove o começo da string - 12 é o tamanho da palavra [background]
  var backgroundValue2 = string.substr(firstIndex + 12, string.length);

  //Remove o final da string
  backgroundValue2 = backgroundValue2.substr(0, backgroundValue2.lastIndexOf("[background]"));

  console.log(backgroundValue2);
}

  • Thank you for the reply!

1

Another way is by using .split() picking up the index [1]:

var string = "Hello [background]image.png[background] World!";
var novo = string.split("[background]")[1];
console.log(novo);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.