简体   繁体   English

Javascript:检查字符串定界符之间是否有空格

[英]Javascript: Check if there is any space between a string delimiter

I need to trim out or add a space to any word before or after any slash(/) located within the string. 我需要在位于字符串内的任何斜杠(/)之前或之后的任何单词上修剪或添加空格。

var str = 'some/value    /even /more   /text';

// should ideally be equal to this 'some /value /even / more text'


I managed to get this to work using .split() and .join() 我设法使用.split().join() .split()起作用

var text = $(this).val();
var arr = text.split('/');

for(var i=0, limit = arr.length; i < limit; i++) {
   arr[i] = $.trim(arr[i]);
}

arr.join(' / ');


but the I think this could be further optimized with regular expressions. 但是我认为可以使用正则表达式进一步优化它。

str = str.replace(/\s*\/\s*/g, ' / ');

Do you mean something like that? 你的意思是那样吗?

var str = this.value.replace(/\s*\/\s*/g, " / ");

It can also be done with: 也可以通过以下方式完成:

 var str = this.value.match(/[^ /]+/g).join(" / "); 

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

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