Emanuel Permane
Emanuel Permane

Reputation: 53

How can I partially match these 2 strings in javascript

So to make this easier Ill provide contents of certain variables.

{{element url}} contains the string I want to compare (which is also an url)
{{url}} Only contains my current url path
{{ArrayObject}} contains a set similar to below 

.

function() {
var data= [
{ url:     "ReplaceThis",
elementUrl:     "ReplaceThis",
category:     "ReplaceThis",
action:     "ReplaceThis",
label:  "ReplaceThis",
value : "ReplaceThis"
  }
];
    return data;
}

The code I am having trouble with for example is this one.

function() {
try{
  var elementurl = "{{element url}}";
  var url = "{{url}}";
  var arrObj = {{ArrayObject}};
  var check = false;
  var ctr;
  for (i = 0; i < arrObj .length; i++) { 
    if (elementurl.lastIndexOf(arrObj[i].elementUrl,0)===0 &&    url.lastIndexOf(arrObj[i].url, 0)===0) {
    check = true;
    ctr=i;
}        
  }
if (check == true){
return arrObj[ctr].action;
}else{

return {{event}};
}
}catch(err) {
    return ; err.message;
}
}

As you can see the line that contains if

(elementurl.lastIndexOf(arrObj[i].elementUrl,0)===0 &&

I tried to replace with this

if (elementurl.IndexOf(arrObj[i].elementUrl) != -1 &&    url.lastIndexOf(arrObj[i].url, 0)===0) {

I've tried several things and essentially what I want to do is arrObj[i].elementUrl will contain a partial elementurl

For example elementUrl may contain oogle.com but elementurl contains google.com how can i tweak my link to support this or something like oogl would match google.com as well for example.

Thoughts?

Upvotes: 1

Views: 528

Answers (2)

Emanuel Permane
Emanuel Permane

Reputation: 53

Jack's idea seems to have worked the best. I can partial match nicely using indexof like he suggested. The exact change I made was

if (elementurl.lastIndexOf(arrObj[i].elementUrl,0)===0 &&    url.lastIndexOf(arrObj[i].url, 0)===0) {

to

if (elementurl.indexOf(arrObj[i].elementUrl) > -1 &&    url.lastIndexOf(arrObj[i].url, 0)===0) {

thanks you for all the replies.

Upvotes: 0

Juank
Juank

Reputation: 6196

To be honest I don't understand your question but if you are trying to match strings based on patterns you can use regular expressions.

var url1 = 'http://www.google.com/something',
    url2 = 'google.com';

if ((new RegExp(url2)).test(url1)){
    // google.com exists in http://www.google.com/something
}

if ((new RegExp(url1)).test(url2)){
    // this wont happen, http://www.google.com/something is no a part of google.com
}

Regexes are really powerfull, you can do a google search for plenty of tutorials on this subject.

Upvotes: 1

Related Questions