I'm looking for a way to separate string from an array object, coming from an API, for example: PageViews, Page Views, I'm using VUEJS.
I'm looking for a way to separate string from an array object, coming from an API, for example: PageViews, Page Views, I'm using VUEJS.
I've done an example to implement in your code:
var regx1 = texto.match (/ [A-Z] / gm) [1]: In this line I get the second occurrence of uppercase letter
V
.
text = text.replace (regx1, '' + regx1): In this line I change
V
by space and re-enter it with all text after it.
new Vue({
el: '#app',
data: {
stringOriginal: 'PageViews'
},
methods: {
stringSeparada() {
var texto = this.stringOriginal;
var regx1 = texto.match(/[A-Z]/gm)[1];
texto = texto.replace(regx1,' '+regx1);
return texto
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script><divid="app">
<input type="text" v-model="stringOriginal" /> <br/>
<p>
Separada: {{ stringSeparada() }}
</p>
</div>
I believe the simplest way would be to just use the String.replace()
with a regex that will match only uppercase.
If you read this session of the documentation of String.replace()
, you will see that the second parameter can be a function or a string. If you use a string you can use some special characters to gain some more functionality. These characters are:
$&
: Replaces with the married string. Ex.:
"...abc123def...".replace(/\d+/, '{{$&}}')
// output: "...abc{{123}}def..."
$'
: Replaces the previous part with the married string
"...abc123def...".replace(/\d+/, '{{$'}}')
// output: "...abc{{...abc}}def..."
$'
: Replace with the back part of the married string
"...abc123def...".replace(/\d+/, "{{$'}}")
// output: "...abc{{def...}}def..."
$n
: Replace with the nth married group in Regex
"00011122233".replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4")
// output: "000.111.222-33"
So you just have to do a simple replace with the regex and it would be solved:
"PageView".replace(/[A-Z]/g, " $&").trim()
* I used the trim to remove the space if the first letter is uppercase. It's simpler than creating a more complex Regex.
In the final version of the code I added "support" to the accent. Actually the "support" is for a very specific range based on the answers this question .
Below the final code, simple and functional:
var regex = /([A-ZÀ-Þ])/gu;
new Vue({
el: '#app',
data: { original: 'PageViewÁcentoTeste'},
computed: {
modificada: function() {
return this.original.replace(regex, ' $1').trim();
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script><divid="app">
<input v-model="original">
<span>"{{ modificada }}"</span>
</div>