Reputation: 81
I have some code where I am getting certain text from a string, but I want the output to have no spaces. I have tried putting .replace(' ', '');
I certain parts of the code but it always stops the code from running
Here is the code im using below, it will output this text
but I want it to output thistext
<div id="text"></div>
var text ='blah blah text-name="this text"';
const gettext = text;
const gettextoutput = [];
const re = /text-name="([^"]+)"/g;
let match;
while ((match = re.exec(gettext)) !== null) {
gettextoutput.push(match[1]);
}
$("#text").append(gettextoutput);
Upvotes: 0
Views: 343
Reputation: 762
Man, you can do it using vanilla javascript:
'text with spaces'.split(' ').join('')
Also, your initial code was on the right way. Try this:
'text with spaces'.replace(/\s/g, '')
Upvotes: 0
Reputation: 10096
Since you are assigning the matches to an array, you have to replace the spaces of all elements of that array, otherwise JavaScript will throw an error since Arrays don't have a replace
method.
var text ='blah blah text-name="this text"';
const gettext = text;
const gettextoutput = [];
const re = /text-name="([^"]+)"/g;
let match;
while ((match = re.exec(gettext)) !== null) {
gettextoutput.push(match[1]);
}
$("#text").append(gettextoutput.map(e => e.replace(" ", "")));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text"></div>
Upvotes: 1