1

How could I hyphenate a string in AngularJS. I would like to be able to do something like this:

<a href="/houses/{{object.name | lowercase | hyphenate}}/">

So that This Is The String becomes this-is-the-string.

Is there a filter to hyphenate strings similar to lowercase? If not any ideas on how I could achieve this?

1
  • Couldn't you just use a regex to detect and then replace the spaces with hypens? Commented Dec 22, 2016 at 16:28

4 Answers 4

6

{{'This Is The String'.toLowerCase().split(' ').join('-')}}

In your case: <a href="/houses/{{object.name.toLowerCase().split(' ').join('-')}}/">

Sign up to request clarification or add additional context in comments.

1 Comment

@greorgy, thanks I didn't realise I could use javascript functions like that in AngularJS, makes sense & works perfectly
0

You can make your own filters in Angular:

app.filter('hyphenate', function() {

  return function(input) {
    output = input.split(' ').join('-');
    return output;
  }

});

Comments

0

You can use the following fiddle on how to write the filter you asked for : https://jsfiddle.net/1x2p5v6g/4/

Filter :

app.filter('myFilter', function() {
    return function(x) {
        if(x == undefined)
        return "";
        return x.replace(/\s/g , '-');
    };
});

Usage :

{{ variable| myFilter}}

Comments

0

Better to create a function or directive

function slugify() {
    return function (input) {
        if (!input)
            return;

        // make lower case and trim
        var slug = input.toLowerCase().trim();

        // replace invalid chars with spaces
        slug = slug.replace(/[^a-z0-9\s-]/g, ' ');

        // replace multiple spaces or hyphens with a single hyphen
        slug = slug.replace(/[\s-]+/g, '-');

        return slug;
    };
}

Now in html

<a href="/houses/{{slugify(object.name)}}/">....</a>

This will remove all the invalid characters which are not allowed in URL.

Comments

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.