简体   繁体   English

Javascript正则表达式-删除字符串中除单词之间的所有空格

[英]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. 我有一个jquery模态对话框窗体,该窗体绑定到手风琴中表格的click事件。 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? 如何删除CLIENT NAME FOO BAR BUZZ周围的空间,而不是其中的空间?

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

jQuery has a built-in $.trim . jQuery具有内置的$.trim In modern browsers there's String.prototype.trim : 在现代浏览器中,存在String.prototype.trim

$.trim(text); // jQuery

// OR

text.trim(); // modern browsers

尝试使用.trim()

var trimmed = client.trim();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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