0
Input data = '/hello/world/test'

I need output like 'hello-world-test' in jquery.

I have tried splice,replace method and also a customize condition(sample code below). But still im not able to get the result.

var split_data=data.split('/');
var new_data='';
        $.each(split_data,function(x){
            if(x!=0){
                new_data=split_data[x]+'-'
            }
        });
        console.log("new"+new_data); // Output : hello-world-test-

Here again I have to remove the last hypen in the output string. So is there anyway to accomplish my output.

By the way Im not expert in jquery.

gdoron
  • 147,333
  • 58
  • 291
  • 367
Darknight
  • 1,132
  • 2
  • 13
  • 31
  • Have a look at this URL. you need to replace all occurenences and then take substring from position '1' to length -1 of a string. http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript – sohail.hussain.dyn Oct 26 '13 at 20:08

1 Answers1

2

Just use regex and slice the first char:

str = str.slice(1).replace(/\//g,'-');

replace on MDN

Live DEMO

You really shouldn't use jQuery for string manipulations

gdoron
  • 147,333
  • 58
  • 291
  • 367