0

I need some assistance with correctly implementing a method that uses .split and .replace to format a string value passed to it.

The string value is 90% of the time an HTML link as per this example: <a href=\"http://www.fnb.co.za\" rel=\"nofollow\">SMC RBJacobs</a>. But sometimes it only contains a normal string value such as: SMC RBJacobs.

I thought it would be a good idea to evaluate the value by checking .indexOf('</a>'), but this evaluates to true all the time.(?) I then get an error in the next statements executed in my method.

Here is my method:

if (col.name === 'twitter_tweet.source') {
    var str = value;
    if (value != null || value != undefined) {
        if (value.indexOf('</a>')) {
            var parts = str.split('"nofollow\">');
            var value = parts[1].replace('</a>', '');
            return value;
        }
    }
    return value;
}

The desired output regardless of whether the string contains HTML markup or not: SMC RBJacobs (or whichever name is passed)

Any help would be appreciated!

3
  • 1
    better use regexp, its better for me in that type of issues. Commented Feb 16, 2017 at 7:05
  • 2
    .indexOf() returns -1 if the search value has not been found, hence the if condition is wrong and should be if (value.indexOf('</a>') > -1) { ... } Commented Feb 16, 2017 at 7:09
  • @ÁlvaroTouzón that is a good idea. Do you perhaps have something in mind that will work in this situation? Commented Feb 16, 2017 at 7:15

2 Answers 2

3

indexOf always returns a number, not a boolean. If found, the index will be zero or more. If not found the index will be -1. So you want to check like:

if (value.indexOf('</a>') > -1) {

If you can have different tags and spacing I would suggest using something less brittle like jQuery:

if ($(value).length) {
  return $(value).text();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I can't believe it slipped my mind (returning a value and not a boolean)! Thank you for your help!
0

I'd try following approach:

var str = '<a href=\"http://www.fnb.co.za\" rel=\"nofollow\">SMC RBJacobs</a>',
el = document.createElement('div'),
result;

el.innerHTML = str;
result = el.textContent;

console.log(result);

Note #1: I assume here that HTML string is safe. Note #2: str can be an HTML or string.

Working example: https://jsfiddle.net/655uqc0f/

1 Comment

Thanks for the help. I am retrieving the value from a DB through, and not from my view. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.