简体   繁体   中英

Javascript regex- remove all spaces in string except between words

I have a bit of a conundrum.

I have a jquery modal dialog form that is bound to a click event of a table within an accordion. On click of a row, the dialog opens up with the input fields and other elements populated with the table row data.

As part of the form, I'd like to include the accordion header text. I can extract out the text via

var activeClient = $("#strat_key_management").accordion("option", "active");
var client = $("#strat_key_management h2").eq(activeClient).text();

but there are many newlines and spaces within the text, as shown:

"\n                         CLIENT NAME FOO BAR BUZZ   \n                           \n                              \n                          \n                      "

I can remove the newlines via

client = client.replace(/\n\gm, "");

and this produces

"                           CLIENT NAME FOO BAR BUZZ   "

where the quotes show the beginning and end of the string.

How can I remove the spaces surrounding CLIENT NAME FOO BAR BUZZ but not within?

使用.replace(/^\\s+|\\s+$/g,"")修剪字符串开头和结尾的空格。

jQuery has a built-in $.trim . In modern browsers there's String.prototype.trim :

$.trim(text); // jQuery

// OR

text.trim(); // modern browsers

尝试使用.trim()

var trimmed = client.trim();

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