从文本区匹配一个单词

matching a word from the textarea

本文关键字:一个 单词 文本区      更新时间:2023-09-26

我试图匹配文字策略与#从一个文本区域

 var start=/#/ig; // # Match
 var word=/#('w+)/ig; //#abc Match
 var content=$('#text').val();
 var go= content.match(start); //Content Matching #
 var name= content.match(word); //Content Matching #abc

在这里,它检查文本区域中的值并给出以#开头的输出单词如果有两个匹配,它显示两个匹配,但我只需要最后一个匹配

.match()函数返回一个匹配数组。

如果你想选择最后一个元素,你需要像这样选择它:

name[name.length-1];
  • name.length返回
  • 元素的个数
  • -1,因为数组键以0开始而不是1

这是小提琴,感谢Dave Briand

试试这个

content = "~test content ~thanks ok ~fine";    
strFine = content.lastIndexOf('~');

给出最后匹配字符或单词或字符串的索引。

方法match通常返回一个数组。要获得最后的匹配,您可以使用以下命令:

var name= content.match(word);
var lastMatch = (!!name) ? name.pop() : name;

如果没有匹配,该方法返回null,并且您要确保不要尝试将null作为数组操作。

这个怎么样?

 var text = $('textarea').val();   // "#maxi kcdjnd dcjjncd #ijicd" 
 //Find all ocurrences of words starting with # and ending in space, period or end of text
 var lastMatch = text.match(/(#.*?)('s|$|'.)/g).pop();
 // match returns ["maxi", "#ijicd"]. pop will get the last element