JQuery - Remove part of string and keep the rest
-
07-06-2021 - |
Frage
I'm receiving multiple strings from a API and sometimes I have a string that looks like this.
first part <!-- Slut på Mall: variable --> second part
I want to use jQuery to exclude the part before and the "Slut... variable -->". Leaving me with the second part.
Just to be clear, the variable is dynamic and will change.
I have been playing around with replace, and match but so far I have failed. I have understood that regex is the way to go
regex = /Mall:.*\s+-->(.*)\z/
But I don't know what function to use with that?
Lösung
var secondPart = "<!--" + yourApiString.split("<!--")[1];
Will return <!-- Slut på Mall: variable --> second part
Andere Tipps
If you wanted to still use a regex and replace, this is how you could go about it.
var x = "first part <!-- Slut på Mall: variable --> second part";
var y = x.replace(/.*<!--/, "<!--");
This replaces everything before <!--
including those four characters but ends up placing them back in.
If you just wanted "second part", then you could just do the following:
var y = x.replace(/.*-->/, "");
Thereby removing every character leading up to -->
and itself.