从另一个url或字符串中提取字符串

extracting a string out of another url or string

本文关键字:字符串 提取 另一个 url      更新时间:2023-09-26

我想从url或某个标题字符串中提取商店/品牌名称。

所以url可能类似于

"http://www.store1.com/brand1-Transform-Ultra-Prepaid-/"
and title could be " brand1 Transform Ultra Prepaid Phone "

我会把可能的商店名称保存在像这样的数组中

var store_array  = ['store1', 'brand1', 'brand2']

比方说,如果我搜索上面的url或标题,结果应该是store1和brand1。

如何在jquery中做到这一点,我是初学者,请详细解释我。

我最初的想法是我应该在下面,但不确定。请帮忙。

$.each( store_array, function(index, value) { 

//在这里做什么});

你可以做:

var url = 'http://www.store1.com/brand1-Transform-Ultra-Prepaid-/',
    path = url.split('/');
var store_array = path[path.length-2].split('-');

演示:http://jsfiddle.net/jcGsp/

这完全取决于你希望它的动态程度,另一个选项是regexp:

var url = 'http://www.store1.com/brand1-Transform-Ultra-Prepaid-/';
var store_array = url.replace(/http:'/'/www.store1.com'/([^'/]+)'//,'$1').split('-');

演示:http://jsfiddle.net/fSpr3/

您可以使用split函数:假设url是:

url=window.location.href;
url.split('http://www.store1.com/');
title=url[1];

如果"brand1 Transform Ultra预付费-"中需要的单词是"brand1",则将其再次拆分为:

title.split('-');
fixed_title=title[0];

我会定义一个函数来进行匹配,并在我感兴趣的字符串上运行它

function findMatches( str ){
   return store_array.filter( function( el ){
    return new RegExp( "'b"+el+"'b", "i" ).test( str );
   });
}
var results1 = findMatches( 'http://www.store1.com/' );
var results2 = findMatches( " brand1 Transform Ultra Prepaid Phone " );
//etc

''b确保"store1"etc是完整的单词(因此,"store 1"与"megastore1"不匹配),/i使其不区分大小写。

array.filter在数组的每个成员上运行一个函数,并返回数组的一个副本,该副本只包含函数返回true的成员。请注意,array.filter是IE9及以上版本(您没有指定平台),对于其他浏览器,这里有anice polyfillhttps://gist.github.com/1031656

findMatches函数遍历列表中的所有字符串,将它们转换为正则表达式,并检查是否在字符串中找到它。如果你有很多测试字符串,运行的索引可能会更有效

function findMatches( str ){
   return store_array.filter( function( el ){
    return ( "-1" !== str.indexOf( el ) );
   });
}

两者都可以。请注意,这不是使用jQuery,而是使用纯JS(尽管是ECMA5)