简体   繁体   中英

Remove text space from a JavaScript

This is a simple one for JS programmers. Base on this demo, https://codepen.io/gschier/pen/jkivt

I want 'The pen is simple.' to be 'The pen issimple.' To remove the space after 'is'.

I tried different areas with no luck. I only know CSS and HTML but not so much JS.

Of course this doesn't make sense with this demo example, I want to start it with an alphabet to make a sentence, for example

 <h1>A <span class="txt-rotate" data-period="2000" data-rotate='[ " great day.", "pple.", "wesome.", " shinny diamond."]'></span>

With the current JS result, I get "A great day.", "A pple.", "A wesome.", "A shinny diamond." Please advise how do I remove the extra space. Thank you.

Try removing space / new line after A

<h1>A<span
     class="txt-rotate"
     data-period="2000"
     data-rotate='[ " great day.", "pple.", "wesome.", " shinny diamond."]'></span>

Working Demo

https://codepen.io/aswinkumar863/pen/NWpEygj

There are multiple solutions, for me the easiest and most convenient is just like below.

 $(document).ready(function(){ var value=$(".txt-rotate").attr('data-rotate'); val_array=JSON.parse(value); var array = val_array.map(function (el) { return el.trim(); }); array = '\'' + array.join('\',\'') + '\''; array="["+array+"]"; $(".txt-rotate").attr('data-rotate',array); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1>A <span class="txt-rotate" data-period="2000" data-rotate='[ " great day.", "pple.", "wesome.", " shinny diamond."]'></span>

you can use replace(/ +/g, ' ') remove multiple space

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM