Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如果检测到空白,如何分割字符串?_Javascript_Regex_String - Fatal编程技术网

Javascript 如果检测到空白,如何分割字符串?

Javascript 如果检测到空白,如何分割字符串?,javascript,regex,string,Javascript,Regex,String,我有几根线一根接一根进来。如果它们的长度超过15个字符,我希望在15个字符之后切片所有内容,但不要在检测到空白之前(以保持可读性) 我目前的逻辑是这样的: const text = "Microsoft Server 2012 R2"; // text.length = 24 let newStr = ''; if(text.length > 15 ){ // true

我有几根线一根接一根进来。如果它们的长度超过15个字符,我希望在15个字符之后切片所有内容,但不要在检测到空白之前(以保持可读性)

我目前的逻辑是这样的:

                const text  = "Microsoft Server 2012 R2"; // text.length = 24
                let newStr = '';
                if(text.length > 15 ){ // true
                    newStr = text.slice(0, 15)
                }
                console.log(newStr);
                // Desired output: "Microsoft Server
                // Current output: "Microsoft Serve"

您可以使用这个正则表达式替换来完成您的工作。这与输入中前15个字符后的0个或多个非空白字符相匹配

var s='Microsoft Server 2012 R2'
var r=s.replace(/^(.{15}\s*).$/,“$1”)
console.log(r)
//=>Microsoft Server
您可以将前15个字符与
[^]{15}
/
[\s\s]{15}
匹配,然后将0个或更多非空白字符与
\s*
匹配:

const text=“Microsoft Server 2012 R2”;
让newStr=(m=text.match(/^[^]{15}\S*/)?m[0]:“”;

console.log(newStr)您可以匹配第一个想要的字母并获取字符,直到找到空格

var string=“Microsoft Server 2012 R2”,
short=string.match(/^.{15}[^]*/)[0];
控制台日志(短)

调用此函数并检查子字符串中的空白,即子文本,它是文本的子字符串,直到15个字符。因此,如果子字符串包含空格,您将得到一个boolen值。此函数还将测试是否存在制表符。

split
返回一个数组,我认为它不是您想要的数组。因此,如果单词中有15个字符,您希望保留整个单词还是删除整个单词?@MasterYushi您是对的,它是slice。对不起,我在测试一些东西。@Luke保留它:)您想截断字符串,还是将字符串一分为二(或更多)?替换
是否比使用
RegExp
执行相同的逻辑然后获取第一组更有效?或者仅仅是为了简短,仅仅是为了简短@AxelH。我们可以执行
exec
match
并获得匹配的字符串。
function hasWhiteSpace(SubText) {
  return /\s/g.test(SubText);
}