replacing spaces in a string with hyphens - javascript

I have a string and I need to fix it in order to append it to a query.
Say I have the string "A Basket For Every Occasion" and I want it to be "A-Basket-For-Every-Occasion"
I need to find a space and replace it with a hyphen. Then, I need to check if there is another space in the string. If not, return the fixed string. If so, run the same process again.
Sounds like a recursive function to me but I am not sure how to set it up. Any help would be greatly appreciated.

You can use a regex replacement like this:
var str = "A Basket For Every Occasion";
str = str.replace(/\s/g, "-");
The "g" flag in the regex will cause all spaces to get replaced.
You may want to collapse multiple spaces to a single hyphen so you don't end up with multiple dashes in a row. That would look like this:
var str = "A Basket For Every Occasion";
str = str.replace(/\s+/g, "-");

Use replace and find for whitespaces \s globally (flag g)
var a = "asd asd sad".replace(/\s/g,"-");
a becomes
"asd-asd-sad"

Try
value = value.split(' ').join('-');
I used this to get rid of my spaces. Instead of the hyphen I made it empty and works great. Also it is all JS. .split(limiter) will delete the limiter and puts the string pieces in an array (with no limiter elements) then you can join the array with the hyphens.

Related

Regex trying to match characters before and after symbol

I'm trying to match characters before and after a symbol, in a string.
string: budgets-closed
To match the characters before the sign -, I do: ^[a-z]+
And to match the other characters, I try: \-(\w+) but, the problem is that my result is: -closed instead of closed.
Any ideas, how to fix it?
Update
This is the piece of code, where I was trying to apply the regex http://jsfiddle.net/trDFh/1/
I repeat: It's not that I don't want to use split; it's just I was really curious, and wanted to see, how can it be done the regex way. Hacking into things spirit
Update2
Well, using substring is a solution as well: http://jsfiddle.net/trDFh/2/ and is the one I chosed to use, since the if in question, is actually an else if in a more complex if syntax, and the chosen solutions seems to be the most fitted for now.
Use exec():
var result=/([^-]+)-([^-]+)/.exec(string);
result is an array, with result[1] being the first captured string and result[2] being the second captured string.
Live demo: http://jsfiddle.net/Pqntk/
I think you'll have to match that. You can use grouping to get what you need, though.
var str = 'budgets-closed';
var matches = str.match( /([a-z]+)-([a-z]+)/ );
var before = matches[1];
var after = matches[2];
For that specific string, you could also use
var str = 'budgets-closed';
var before = str.match( /^\b[a-z]+/ )[0];
var after = str.match( /\b[a-z]+$/ )[0];
I'm sure there are better ways, but the above methods do work.
If the symbol is specifically -, then this should work:
\b([^-]+)-([^-]+)\b
You match a boundry, any "not -" characters, a - and then more "not -" characters until the next word boundry.
Also, there is no need to escape a hyphen, it only holds special properties when between two other characters inside a character class.
edit: And here is a jsfiddle that demonstrates it does work.

Remove string after predefined string

I am pulling content from an RSS feed, before using jquery to format and edit the rss feed (string) that is returned. I am using replace to replace strings and characters like so:
var spanish = $("#wod a").text();
var newspan = spanish.replace("=","-");
$("#wod a").text(newspan);
This works great. I am also trying to remove all text after a certain point. Similar to truncation, I would like to hide all text starting from the word "Example".
In this particular RSS feed, the word example is in every feed. I would like to hide "example" and all text the follows that word. How can I accomplish this?
Though there is not enough jQuery, you even don't need it to remove everything after a certain word in the given string. The first approach is to use substring:
var new_str = str.substring(0, str.indexOf("Example"));
The second is a trick with split:
var new_str = str.split("Example")[0];
If you also want to keep "Example" and just remove everything after that particular word, you can do:
var str = "aaaa1111?bbb&222:Example=123456",
newStr = str.substring(0, str.indexOf('Example') + 'Example'.length);
// will output: aaaa1111?bbb&222:Example
jQuery isn't intended for string manipulation, you should use Vanilla JS for that:
newspan = newspan.replace(/example.*$/i, "");
The .replace() method accepts a regular expression, so in this case I've used /example.*$/i which does a case-insensitive match against the word "example" followed by zero or more of any other characters to the end of the string and replaces them with an empty string.
I would like to hide all text starting from the word "Example"
A solution that uses the simpler replace WITH backreferences so as to "hide" everything starting with the word Example but keeping the stuff before it.
var str = "my house example is bad"
str.replace(/(.*?) example.*/i, "$1") // returns "my house"
// case insensitive. also note the space before example because you
// probably want to throw that out.

Javascript regex expression to replace multiple strings?

I've a string done like this: "http://something.org/dom/My_happy_dog_%28is%29cool!"
How can I remove all the initial domain, the multiple underscore and the percentage stuff?
For now I'm just doing some multiple replace, like
str = str.replace("http://something.org/dom/","");
str = str.replace("_%28"," ");
and go on, but it's really ugly.. any help?
Thanks!
EDIT:
the exact input would be "My happy dog is cool!" so I would like to get rid of the initial address and remove the underscores and percentage and put the spaces in the right place!
The problem is that trying to put a regex on Chrome "something goes wrong". Is it a problem of Chrome or my regex?
I'd suggest:
var str = "http://something.org/dom/My_happy_dog_%28is%29cool!";
str.substring(str.lastIndexOf('/')+1).replace(/(_)|(%\d{2,})/g,' ');
JS Fiddle demo.
The reason I took this approach is that RegEx is fairly expensive, and is often tricky to fine tune to the point where edge-cases become less troublesome; so I opted to use simple string manipulation to reduce the RegEx work.
Effectively the above creates a substring of the given str variable, from the index point of the lastIndexOf('/') (which does exactly what you'd expect) and adding 1 to that so the substring is from the point after the / not before it.
The regex: (_) matches the underscores, the | just serves as an or operator and the (%\d{2,}) serves to match digit characters that occur twice in succession and follow a % sign.
The parentheses surrounding each part of the regex around the |, serve to identify matching groups, which are used to identify what parts should be replaced by the ' ' (single-space) string in the second of the arguments passed to replace().
References:
lastIndexOf().
replace().
substring().
You can use unescape to decode the percentages:
str = unescape("http://something.org/dom/My_happy_dog_%28is%29cool!")
str = str.replace("http://something.org/dom/","");
Maybe you could use a regular expression to pull out what you need, rather than getting rid of what you don't want. What is it you are trying to keep?
You can also chain them together as in:
str.replace("http://something.org/dom/", "").replace("something else", "");
You haven't defined the problem very exactly. To get rid of all stretches of characters ending in %<digit><digit> you'd say
var re = /.*%\d\d/g;
var str = str.replace(re, "");
ok, if you want to replace all that stuff I think that you would need something like this:
/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g
test
var string = "http://something.org/dom/My_happy_dog_%28is%29cool!";
string = string.replace(/(http:\/\/.*\.[a-z]{3}\/.*\/)|(\%[a-z0-9][a-z0-9])|_/g,"");

Reversing a string

I want to reverse a string, then I want to reverse each word in it. I was able to reverse the string. But couldn't reverse words in it.
Given Str = "how are you"
Expected Result = "you are how"
My code
var my_str="how are you";
alert(my_str.split('').reverse().join(''));
Result I get: uoy era woh
How to get the final result??
the other answers are entirely correct if your string has only 1 space between words.
if you have multiple spaces between words, then things are a bit different:
to get just the words, in reverse order, rejoined by 1 space:
str.split(/\s+/).reverse().join(" ")
to reverse the entire string, and still have the original whitespace:
str.split(/\b/).reverse().join('')
the first one uses a regex, "/\s+/", to match an entire run of spaces, instead of a single space. it rejoins the words with a single space.
the second one uses a regex, "/\b/", to just split on the boundaries between words and non-words. since the runs of spaces will be preserved, it just rejoins with an empty string.
I think you've got an empty string in there: my_str.split('')
Make sure you put a space: my_str.split(' ')
The problem is you are splitting with the empty string instead of the space character. Try this:
var str = "how are you";
alert(str.split(" ").reverse().join(" "));
Try it here.
If you are using ES6 then you could use this -
let myStr="How are you";
console.log([...myStr].reverse().join(''));

Deleting empty spaces in a string

Okay I have a simple Javascript problem, and I hope some of you are eager to help me. I realize it's not very difficult but I've been working whole day and just can't get my head around it.
Here it goes: I have a sentence in a Textfield form and I need to reprint the content of a sentence but WITHOUT spaces.
For example: "My name is Slavisha" The result: "MynameisSlavisha"
Thank you
You can replace all whitespace characters:
var str = "My name is Slavisha" ;
str = str.replace(/\s+/g, ""); // "MynameisSlavisha"
The /\s+/g regex will match any whitespace character, the g flag is necessary to replace all the occurrences on your string.
Also, as you can see, we need to reassign the str variable because Strings are immutable -they can't really change-.
Another way to do it:
var str = 'My name is Slavisha'.split(' ').join('');

Categories