How can I trim the leading and trailing comma in javascript? - javascript

I have a string that is like below.
,liger, unicorn, snipe,
how can I trim the leading and trailing comma in javascript?

because I believe everything can be solved with regex:
var str = ",liger, unicorn, snipe,"
var trim = str.replace(/(^,)|(,$)/g, "")
// trim now equals 'liger, unicorn, snipe'

While cobbal's answer is the "best", in my opinion, I want to add one note: Depending on the formatting of your string and purpose of stripping leading and trailing commas, you may also want to watch out for whitespace.
var str = ',liger, unicorn, snipe,';
var trim = str.replace(/(^\s*,)|(,\s*$)/g, '');
Of course, with this application, the value of using regex over basic string methods is more obvious.

If you want to make sure you don't have any trailing commas or whitespace, you might want to use this regex.
var str = ' , , , foo, bar, ';
str = str.replace(/(^[,\s]+)|([,\s]+$)/g, '');
returns
"foo, bar"

Try this, since not everything can be solved by REs and even some things that can, shouldn't be :-)
<script type="text/javascript">
var str = ",liger, unicorn, snipe,";
if (str.substr(0,1) == ",") {
str = str.substring(1);
}
var len = str.length;
if (str.substr(len-1,1) == ",") {
str = str.substring(0,len-1);
}
alert (str);
</script>

In ECMAScript 5 and above, you can now do a one-liner
',liger, unicorn, snipe,'.split(',').map(e => e.trim()).filter(e => e).join(', ')

Related

How do I delete banned characters from a string more than once in JS?

I am trying to create a script that will reduce, for example, "Hello. I had a great day today!" to "helloihadagreatdaytoday". So far I have only managed to convert the text to lower case :^)
I have a string of forbidden characters.
var deletthis = ". !";
var a = deletthis.split("");
As you can see, it bans dot, space and exclamation mark, and turns that string into an array. I then give the user a prompt, and run the return string (q) through a for loop, which should delete the banned characters.
for (i=0; i<a.length; i++) {
q = q.replace(a[i], "");
}
However, this only bans one instance of that character in a string. So if I type "That is nice... Very nice!!!", it would return as "Thatis nice.. Very nice!!".
Any help is appreciated :)!
You can use a regular expression for this.
deletthis.replace(/ /g,'')
what this code does is it finds the whitespaces in a string and deletes them,
moreover, a quick google with how to delete spaces in a string would have helped
Use a regular expression
a = a.replace(/[\.!]/g, "");
If you don't know the characters beforehand, you can escape them just in case:
a = a.replace(new RegExp("[" + deletethis.split(" ").map(c => "\\" + c).join("") + "]", "g"), "");
Use regex to remove anything that is not alphabet then LowerCase() for case conversion and then split and join to remove any space
let str = "Hello. I had a great day today!"
let k = str.replace(/[^a-zA-Z ]/g, "").toLowerCase().split(" ").join("");
console.log(k)
Using regex could be shorter in this case because it's the same output, so we could use | that means or in a regex:
var str = "Hello. I had a great day today!";
str = str.replace(/\.| |!/g, "").toLocaleLowerCase();
console.log(str)

How do I replace all spaces, commas and periods in a variable using javascript

I have tried var res = str.replace(/ |,|.|/g, ""); and var res = str.replace(/ |,|.|/gi, "");. What am I missing here?
var str = "Text with comma, space, and period.";
var res = str.replace(/ |,|.|/g, "");
document.write(res);
If you just want to delete all spaces, commas and periods you can do it like that:
var res = str.replace(/[ ,.]/g, "");
You can also use the | operator, but in that case you have to escape the period, because a plain period will match with any character. As a general remark, if in a regular expression you have multiple alternatives with | that all consist of a single character, it is preferable to use a set with [...].
You need to escape dot \.:
"Text with comma, space and period.".replace(/ |,|\.|/g, "")
You can use these lines:
str = str.replace(/[ ,.]/g,'');
Plus i have added a fiddle for this at Fiddle

Invert brace from { to } and vise versa

I have a string with { and } how can I take all of them and reverse them, so all { become } and } become {?
I can't do this:
str = str.replace("}", "{");
str = str.replace("{", "}");
because that will make A face the same way as B then it will replace B which will all change them to the same direction.
I tried doing this:
str = str.replace(["{", "}"], ["}", "{"]);
But that just doesn't seem to do anything (not even error out).
So, what can I do to invert them?
You could use a regexp with a callback function to solve this:
str.replace(/\{|\}/g, function(match) {
return match == "}" ? "{" : "}";
});
You can use a temporary string that will definitely be unique to do the swap:
str = str.replace("}", "TEMP_HOLDER");
str = str.replace("{", "}");
str = str.replace("TEMP_HOLDER", "{");
But it's prone to a bug if the string contains the temp string and it also doesn't replace more than one occurrence. I'd suggest using Erik's answer.
You need to convert to something else in the first pass, and then convert to what you want after you've made the other conversions.
str = str.replace("{", "_###_");
str = str.replace("}", "{");
str = str.replace("_###_", "}");
Of course, the something else will need to be something that won't otherwise be in your string. You could use "\r\n" if you are sure you string won't contain newlines.
You could go with a two stage solution:
str = str.replace("}", "~");
str = str.replace("{", ",");
str = str.replace("~", "{");
str = str.replace(",", "}");

Splitting string to array while ignoring content between apostrophes

I need something that takes a string, and divides it into an array.
I want to split it after every space, so that this -
"Hello everybody!" turns into ---> ["Hello", "Everybody!"]
However, I want it to ignore spaces inbetween apostrophes. So for examples -
"How 'are you' today?" turns into ---> ["How", "'are you'", "today?"]
Now I wrote the following code (which works), but something tells me that what I did is pretty much horrible and that it can be done with probably 50% less code.
I'm also pretty new to JS so I guess I still don't adhere to all the idioms of the language.
function getFixedArray(text) {
var textArray = text.split(' '); //Create an array from the string, splitting by spaces.
var finalArray = [];
var bFoundLeadingApostrophe = false;
var bFoundTrailingApostrophe = false;
var leadingRegExp = /^'/;
var trailingRegExp = /'$/;
var concatenatedString = "";
for (var i = 0; i < textArray.length; i++) {
var text = textArray[i];
//Found a leading apostrophe
if(leadingRegExp.test(text) && !bFoundLeadingApostrophe && !trailingRegExp.test(text)) {
concatenatedString =concatenatedString + text;
bFoundLeadingApostrophe = true;
}
//Found the trailing apostrophe
else if(trailingRegExp.test(text ) && !bFoundTrailingApostrophe) {
concatenatedString = concatenatedString + ' ' + text;
finalArray.push(concatenatedString);
concatenatedString = "";
bFoundLeadingApostrophe = false;
bFoundTrailingApostrophe = false;
}
//Found no trailing apostrophe even though the leading flag indicates true, so we want this string.
else if (bFoundLeadingApostrophe && !bFoundTrailingApostrophe) {
concatenatedString = concatenatedString + ' ' + text;
}
//Regular text
else {
finalArray.push(text);
}
}
return finalArray;
}
I would deeply appreciate it if somebody could go through this and teach me how this should be rewritten, in a more correct & efficient way (and perhaps a more "JS" way).
Thanks!
Edit -
Well I just found a few problems, some of which I fixed, and some I'm not sure how to handle without making this code too complex (for example the string "hello 'every body'!" doesn't split properly....)
You could try matching instead of splitting:
string.match(/(?:['"].+?['"])|\S+/g)
The above regex will match anything in between quotes (including the quotes), or anything that's not a space otherwise.
If you want to also match characters after the quotes, like ? and ! you can try:
/(?:['"].+?['"]\W?)|\S+/g
For "hello 'every body'!" it will give you this array:
["hello", "'every body'!"]
Note that \W matches space as well, if you want to match punctuation you could be explicit by using a character class in place of \W
[,.?!]
Or simply trim the strings after matching:
string.match(regex).map(function(x){return x.trim()})

Regex to replace all but the last non-breaking space if multiple words are joined?

Using javascript (including jQuery), I’m trying to replace all but the last non-breaking space if multiple words are joined.
For example:
Replace A String of Words with A String of Words
I think you want something like this,
> "A String of Words".replace(/ (?=.*? )/g, " ")
'A String of Words'
The above regex would match all the   strings except the last one.
Assuming your string is like this, you can use Negative Lookahead to do this.
var r = 'A String of Words'.replace(/ (?![^&]*$)/g, ' ');
//=> "A String of Words"
Alternative to regex, easier to understand:
var fn = function(input, sep) {
var parts = input.split(sep);
var last = parts.pop();
return parts.join(" ") + sep + last;
};
> fn("A String of Words", " ")
"A String of Words"

Categories

Resources