I've seen multiple instance of that kind of question, but not the one I'm looking for specifically... (I just hope I'm not hopelessly blind ! :P)
Let's consider this code:
var oneString = "This is a string";
document.write(oneString.replace("is", ""));
I would have assumed that the output would have been:
This a string.
But this is the output I'm getting:
This a string
It's like replace() think that the second argument sent is " " and not ""... What would be the proper manner then to strip the string of a given string, without having extra spaces floating in my output ?
You are actually getting "is" replaced with an empty string, it's the space before and after the "is" you replace that stay around as the two spaces you see. Try;
oneString.replace("is ", "")
Are you sure you're not getting "This a string"?
I think you should replace "is " with "" to get your desired output. There is a space before as well as after the word.
Look at the original string - "This_is_a_string" (I replaced spaces with underscores). When you remove "is", you don't touch either of the surrounding spaces, so both end up in the output. What you need to do is oneString.replace("is","").replace(/ +/," ") -- get rid of "is" and then eliminate any double spaces. If you want to keep some double spaces, try oneString.replace(" is","") instead, though you will run into issues if the string starts with is (eg "is it safe?").
The best answer might be something like oneString.replace(/is ?/,"") to match is possibly followed by a space oroneString.replace(/ ?is ?/," ") to match is possibly surrounded by spaces, and replace all of them with one space.
You didn't include any spaces in your pattern. When I try your code in Chrome I get:
> "This is a string".replace("is","")
"Th is a string"
One way to accomplish what you're trying would be to use a regexp instead:
> "This is a string".replace(/is\s/,"")
"This a string"
var aString = "This is a string";
var find = "is"; // or 'This' or 'string'
aString = aString.replace(new RegExp("(^|\\s+)" + find + "(\\s+|$)", "g"), "$1");
console.log(oneString);
The only case where this isn't perfect is when you replace the last word in the sentence. It will leave one space at the end, but I suppose you could check for that.
The g modifier is to make the replace replace all instances, and not just the first one.
Add the i modifier to make it case insensitive.
If you also want this to work on strings like:
"This has a comma, in it"
Change the regexp to:
var find = "comma";
new RegExp("(^|\\s+)" + find + "(\\s+|$|,)", "g")
Related
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.
I have a string that looks like this: "the word you need is 'hello' ".
What's the best way to put 'hello' (but without the quotes) into a javascript variable? I imagine that the way to do this is with regex (which I know very little about) ?
Any help appreciated!
Use match():
> var s = "the word you need is 'hello' ";
> s.match(/'([^']+)'/)[1];
"hello"
This will match a starting ', followed by anything except ', and then the closing ', storing everything in between in the first captured group.
http://jsfiddle.net/Bbh6P/
var mystring = "the word you need is 'hello'"
var matches = mystring.match(/\'(.*?)\'/); //returns array
alert(matches[1]);
If you want to avoid regular expressions then you can use .split("'") to split the string at single quotes , then use jquery.map() to return just the odd indexed substrings, ie. an array of all single-quoted substrings.
var str = "the word you need is 'hello'";
var singleQuoted = $.map(str.split("'"), function(substr, i) {
return (i % 2) ? substr : null;
});
DEMO
CAUTION
This and other methods will get it wrong if one or more apostrophes (same as single quote) appear in the original string.
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,"");
Looking for a regex/replace function to take a user inputted string say, "John Smith's Cool Page" and return a filename/url safe string like "john_smith_s_cool_page.html", or something to that extent.
Well, here's one that replaces anything that's not a letter or a number, and makes it all lower case, like your example.
var s = "John Smith's Cool Page";
var filename = s.replace(/[^a-z0-9]/gi, '_').toLowerCase();
Explanation:
The regular expression is /[^a-z0-9]/gi. Well, actually the gi at the end is just a set of options that are used when the expression is used.
i means "ignore upper/lower case differences"
g means "global", which really means that every match should be replaced, not just the first one.
So what we're looking as is really just [^a-z0-9]. Let's read it step-by-step:
The [ and ] define a "character class", which is a list of single-characters. If you'd write [one], then that would match either 'o' or 'n' or 'e'.
However, there's a ^ at the start of the list of characters. That means it should match only characters not in the list.
Finally, the list of characters is a-z0-9. Read this as "a through z and 0 through 9". It's a short way of writing abcdefghijklmnopqrstuvwxyz0123456789.
So basically, what the regular expression says is: "Find every letter that is not between 'a' and 'z' or between '0' and '9'".
I know the original poster asked for a simple Regular Expression, however, there is more involved in sanitizing filenames, including filename length, reserved filenames, and, of course reserved characters.
Take a look at the code in node-sanitize-filename for a more robust solution.
For more flexible and robust handling of unicode characters etc, you could use the slugify in conjunction with some regex to remove unsafe URL characters
const urlSafeFilename = slugify(filename, { remove: /"<>#%\{\}\|\\\^~\[\]`;\?:#=&/g });
This produces nice kebab-case filenemas in your url and allows for more characters outside the a-z0-9 range.
Here's what I did. It works to convert full sentences into a decently clean URL.
First it trims the string, then it converts spaces to dashes (-), then it gets rid of anything that's not a letter/number/dash
function slugify(title) {
return title
.trim()
.replace(/ +/g, '-')
.toLowerCase()
.replace(/[^a-z0-9-]/g, '')
}
slug.value = slugify(text.value);
text.oninput = () => { slug.value = slugify(text.value); };
<input id="text" value="Foo: the old #Foobîdoo!! " style="font-size:1.2em">
<input id="slug" readonly style="font-size:1.2em">
I think your requirement is to replaces white spaces and aphostophy `s with _ and append the .html at the end try to find such regex.
refer
http://www.regular-expressions.info/javascriptexample.html
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(''));