计算单词输入字段 [英] Count words input field

查看:83
本文介绍了计算单词输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我需要在输入字段中获取单词数。因此,方法是修剪前导和尾随空格,并将字符串中的剩余空间限制为1.这样我就能获得单词数。以下是我的代码。

Basically I need to get the number of words in an input field. So the approach is to trim the leading and trailing spaces and also to limit the remaining spaces within the string to 1. So that I'll be able to get the number of words. Below is my code to do this.

例如。
输入值:

E.g. input value:

"   Robert   Neil       Cook   " 

预期产出:

3 //"Robert Neil Cook" 

这是我试过的。

var str = $.trim( $('#inval').val() );
var Fstr = str.split(' ').length;
console.log(fstr);


推荐答案

您可以使用 .match (/ \ S + / g)

var str = "   Robert   Neil       Cook   ";
var arr = str.match(/\S+/g);
var newstr = arr.join() 
console.log('length::::>', arr.length);
console.log('newstr::::>', newstr);

这个 .match(/ \ S + / g)会返回没有任何空格的单词作为数组,你可以使用长度它的属性。

This .match(/\S+/g) would return you the words without any space as an array and you can use length property of it.

这篇关于计算单词输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆