I've used below formula to remove all blank space before " and after " but not effort.
var test_string = '{" 1 ": "b.) some pasta salad", " 10": " a.) Yes, some bread", "11 ": " a.) eggs and toast " }'
var test_string_format = test_string.replace(/^[ '"]+|[ '"]+$|( ){2,}/g,'$1')
console.log(test_string_format)
How can I use regex to get the desired output?
{"1":"b.) some pasta salad","10":"a.) Yes, some bread","11":"a.) eggs and toast" }
const regex = /(\s*["]\s*)/gm;
var test_string = = `{" 1 ": "b.) some pasta salad", " 10": " a.) Yes, some bread", "11 ": " a.) eggs and toast " }
`;
console.log(test_string.replace(regex, '"'))
Assuming that the string content is always valid JSON, you can do it like this:
var str = '{" 1 ": "b.) some pasta salad", " 10": " a.) Yes, some bread", "11 ": " a.) eggs and toast " }'
const res=JSON.stringify(Object.fromEntries(Object.entries(JSON.parse(str)).map(e=>e.map(e=>e.trim()))))
console.log(res)
I know, this is kind of a "goofy" solution, but it works for the given sample string.
The snippet parses the JSON string, then converts the resulting object into an array of arrays. Each element of each sub-array is then .trim()-med and at the end of the operation the object is reconstructed via .Object.fromEntries() and turned back into a JSON string via JSON.stringify().
Replace zero or more spaces, followed by a quote, followed by zero or more spaces, with just the quote:
replaceAll(/ *" */g, '"')
const test_string = '{" 1 ": "b.) some pasta salad", " 10": " a.) Yes, some bread", "11 ": " a.) eggs and toast " }'
const trimmed = test_string.replaceAll(/ *" */g, '"');
console.log(trimmed);
const test_string = '{" 1 ": "b.) some pasta salad", " 10": " a.) Yes, some bread", "11 ": " a.) eggs and toast " }';
const test_string_format = test_string.replace(/\s*"\s*/g, '"');
console.log(test_string_format);
\s: matches any white-space character
*: matches zero or more of the prev character(\s)
": matches the double quote character
console.log('{" 1 ": "b.) some pasta salad", " 10": " a.) Yes, some bread", "11 ": " a.) eggs and toast " }'
.replaceAll(/( *\" +)|( +\ *)/ig,'"'))
Related
I have an input field on which the user types the city name, but what if the user types the city like this:
"New York "
" New York "
I used the trim function but that did not work, any suggestion?
const city = "New York ";
console.log(city.trim());
How can I remove all the white spaces so I can save the city in the state as "New York"?
You can also use replace to replace all consecutive space characters with one space:
const str = "New York "
" New York "
const res = str.replace(/\s+/gm, " ").trim()
console.log(res)
Alternatively, you can split the string by a space, filter out the empty items, then join back by a space:
const str = "New York "
" New York "
const res = str.split(" ").filter(e=>e).join(" ")
console.log(res)
Combine the string.replace() method and the RegEx and replace it with a single string. Notice the starting and ending spaces will be kept and stripped down to a single space. Trim any surrounding spaces from the string using JavaScript’s string.trim() method
const city = " New York ";
console.log(city.replace(/\s+/g, ' ').trim());
I'm just beginning my learning process and am stuck now on this one string. I've searched MDN, Google and Bing and not found any help.
My code instructions tell me to assign a variable, which I did. Then it wants me to test in console.log. I've done so, and when I do with spaces and punctuation, it gives me an error saying that it expected an identifier and instead saw '+'.
If I take the punctuation out I don't have an error, but no punctuation. If I take out the extra spaces as well as punctuation, I get a strange run-on sentence but no errors. I'm working this problem in Udacity, it is quiz 24 of lesson 2.
My code is:
var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " + adjective1. + " James and Julia are so " + adjective2. + " I cannot wait to work through the rest of this " + adjective3 + " content!";
console.log(madLib);
You need to add the dots as strings as well.
var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " + adjective1 + "."
+ " James and Julia are so " + adjective2 + "."
+ " I cannot wait to work through the rest of this " + adjective3 + " content!";
console.log(madLib);
The dot . has a special meaning in Javascript. It works as accessor for properties of an object.
Math.floor(1.5); // return the integer value of the given number
Read more here about property accessor.
Add . (dot) inside the double quoted part of string, not next to the variable.
It is a part of string, not a in-memory variable. And you are calling no function after that.
Below snippet works properly.
var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " + adjective1 + ". James and Julia are so " + adjective2 + ". I cannot wait to work through the rest of this " + adjective3 + " content!";
console.log(madLib);
Example of using dot to call a function. It is not required in this case since it is already a string.
var adjective1 = "amazing";
var adjective2 = "fun";
var adjective3 = "entertaining";
var madLib = "The intro to JavaScript course is " + adjective1.toString() + ". James and Julia are so " + adjective2.toString() + ". I cannot wait to work through the rest of this " + adjective3 + " content!";
console.log(madLib);
I have a string which I'd like to split into items contained in an array as the following example:
var text = "I like grumpy cats. Do you?"
// to result in:
var wordArray = ["I", " ", "like", " ", "grumpy", " ", "cats", ".", " ", "Do", " ", "you", "?" ]
I've tried the following expression (and a similar varieties without success
var wordArray = text.split(/(\S+|\W)/)
//this disregards spaces and doesn't separate punctuation from words
In Ruby there's a Regex operator (\b) that splits at any word boundary preserving spaces and punctuation but I can't find a similar for Java Script. Would appreciate your help.
Use String#match method with regex /\w+|\s+|[^\s\w]+/g.
\w+ - for any word match
\s+ - for whitespace
[^\s\w]+ - for matching combination of anything other than whitespace and word character.
var text = "I like grumpy cats. Do you?";
console.log(
text.match(/\w+|\s+|[^\s\w]+/g)
)
Regex explanation here
FYI : If you just want to match single special char then you can use \W or . instead of [^\s\w]+.
The word boundary \b should work fine.
Example
"I like grumpy cats. Do you?".split(/\b/)
// ["I", " ", "like", " ", "grumpy", " ", "cats", ". ", "Do", " ", "you", "?"]
Edit
To handle the case of ., we can split it on [.\s] as well
Example
"I like grumpy cats. Do you?".split(/(?=[.\s]|\b)/)
// ["I", " ", "like", " ", "grumpy", " ", "cats", ".", " ", "Do", " ", "you", "?"]
(?=[.\s] Positive look ahead, splits just before . or \s
var text = "I like grumpy cats. Do you?"
var arr = text.split(/\s|\b/);
alert(arr);
I would like to split a string like that:
"'Hi, how are you?' he said."
in this array:
["'", "Hi", ",", " ", "how", " ", "are", " ", "you", "?", "'", " ", "he", " ", "said", "."]
in my js script. I tried with some regexp, but I'm not very good at using it. Can anyone help me?
This is what I'd probably use:
"'Hi, how are you?' he said.".match(/\w+|./g);
It performs a global match for words (\w+) and other characters (.) in the given string.
"'Hi, how are you?' he said.".match(/\w+|\W/g)
//output
["'", "Hi", ",", " ", "how", " ", "are", " ", "you", "?", "'", " ", "he", " ", "said", "."]
Explanation
\w+ - For Matching Group of Characters
\W - For Matching Non-Character
| - Or operator between above two (either a Character or a non character)
string=string.replace(RegExp(filter[a]+" | "+filter[a],"g"),filter[a])
For some reason, this isn't affecting both the filter followed by the space and the filter with a space in front. Assuming the filter is ",", it would take the second side and only replace " ," rather than " ," and ", ". The filter is user-specified, so I can't use a normal regular expression (which DOES work) such as string=string.replace(/, | ,/g,filter[a])
Can someone explain to me why it doesn't work and how to make it work?
It works for me:
s = 'abc, def,ghi ,klm'
a = ','
s = s.replace(RegExp(a + " | " + a, "g"), a)
"abc,def,ghi,klm"
Remember that you regular expression won't replace " , " with ",". You could try using this instead:
" ?" + filter[a] + " ?"