Turn string into object - javascript

Okay so I know
var str = {}; string.split(' ').forEach(function(val, idx) {str[++idx] = val;});
but if string was " Hello world 'how r u' " it would return
["1":"Hello","2":"world","3":"how","4":"r","5":"u"]
I want it to return
["1":"Hello","2":"world","3":"how r u"]
so things between ' ' and " " are 1 item how do I make it do that?
btw I'm using node.js

Not a node.js guru, so I don't know if there is a nice solution by means of regular expressions in the split function, but a solution might be to write a function to first split up the original string into bigger chunk, based on the " or ' character. This will result in an array of strings, which you can then further split up into smaller chunks.

Thank you louis on swiftirc#javascript for this
var out = {}; 'this is "a test" with a "random string of words" 34iuv 38vy 3b8u nuhvbe7yvb 73rvy dsuh bue "f34fdvedfg wr edf Fw efwef" efg3f'.match(/\w+|"(.[^"]+)"/g).forEach(function (str, idx) { out[++idx] = str.replace(/^"|"$/g,''); });
console.log(out);
>> {"1":"this","2":"is","3":"a test","4":"with","5":"a","6":"random string of words","7":"34iuv","8":"38vy","9":"3b8u","10":"nuhvbe7yvb","11":"73rvy","12":"dsuh","13":"bue","14":"f34fdvedfg wr edf Fw efwef","15":"efg3f"}

Related

New line break every two words in javascript string

I have one string
string = "example string is cool and you're great for helping out"
I want to insert a line break every two words so it returns this:
string = 'example string \n
is cool \n
and you're \n
great for \n
helping out'
I am working with variables and cannot manually do this. I need a function that can take this string and handle it for me.
Thanks!!
You can use replace method of string.
(.*?\s.*?\s)
.*?- Match anything except new line. lazy mode.
\s - Match a space character.
let string = "example string is cool and you're great for helping out"
console.log(string.replace(/(.*?\s.*?\s)/g, '$1'+'\n'))
I would use this regular expression: (\S+\s*){1,2}:
var string = "example string is cool and you're great for helping out";
var result = string.replace(/(\S+\s*){1,2}/g, "$&\n");
console.log(result);
First, split the list into an array array = str.split(" ") and initialize an empty string var newstring = "". Now, loop through all of the array items and add everything back into the string with the line breaks array.forEach(function(e, i) {newstring += e + " "; if((i + 1) % 2 = 0) {newstring += "\n "};})
In the end, you should have:
array = str.split(" ");
var newstring = "";
array.forEach(function(e, i) {
newstring += e + " ";
if((i + 1) % 2 = 0) {
newstring += "\n ";
}
})
newstring is the string with the line breaks!
let str = "example string is cool and you're great for helping out" ;
function everyTwo(str){
return str
.split(" ") // find spaces and make array from string
.map((item, idx) => idx % 2 === 0 ? item : item + "\n") // add line break to every second word
.join(" ") // make string from array
}
console.log(
everyTwo(str)
)
output => example string
is cool
and you're
great for
helping out

How to replace found regex sub string with spaces with equal length in javascript?

In javascript if I have something like
string.replace(new RegExp(regex, "ig"), " ")
this replaces all found regexes with a single space. But how would I do it if I wanted to replace all found regexes with spaces that matched in length?
so if regex was \d+, and the string was
"123hello4567"
it changes to
" hello "
Thanks
The replacement argument (2nd) to .replace can be a function - this function is called in turn with every matching part as the first argument
knowing the length of the matching part, you can return the same number of spaces as the replacement value
In the code below I use . as a replacement value to easily illustrate the code
Note: this uses String#repeat, which is not available in IE11 (but then, neither are arrow functions) but you can always use a polyfill and a transpiler
let regex = "\\d+";
console.log("123hello4567".replace(new RegExp(regex, "ig"), m => '.'.repeat(m.length)));
Internet Exploder friendly version
var regex = "\\d+";
console.log("123hello4567".replace(new RegExp(regex, "ig"), function (m) {
return Array(m.length+1).join('.');
}));
thanks to #nnnnnn for the shorter IE friendly version
"123hello4567".replace(new RegExp(/[\d]/, "ig"), " ")
1 => " "
2 => " "
3 => " "
" hello "
"123hello4567".replace(new RegExp(/[\d]+/, "ig"), " ")
123 => " "
4567 => " "
" hello "
If you just want to replace every digit with a space, keep it simple:
var str = "123hello4567";
var res = str.replace(/\d/g,' ');
" hello "
This answers your example, but not exactly your question. What if the regex could match on different numbers of spaces depending on the string, or it isn't as simple as /d more than once? You could do something like this:
var str = "123hello456789goodbye12and456hello12345678again123";
var regex = /(\d+)/;
var match = regex.exec(str);
while (match != null) {
// Create string of spaces of same length
var replaceSpaces = match[0].replace(/./g,' ');
str = str.replace(regex, replaceSpaces);
match = regex.exec(str);
}
" hello goodbye and hello again "
Which will loop through executing the regex (instead of using /g for global).
Performance wise this could likely be sped up by creating a new string of spaces with the length the same length as match[0]. This would remove the regex replace within the loop. If performance isn't a high priority, this should work fine.

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"

Regular expression to replace words preserving spaces

I'm trying to develop a function in javascript that get a phrase and processes each word, preserving whiteSpaces. It would be something like this:
properCase(' hi,everyone just testing') => ' Hi,Everyone Just Testing'
I tried a couple of regular expressions but I couldn't find the way to get just the words, apply a function, and replace them without touching the spaces.
I'm trying with
' hi,everyone just testing'.match(/([^\w]*(\w*)[^\w]*)?/g, 'x')
[" hi,", "everyone ", "just ", "testing", ""]
But I can't understand why are the spaces being captured. I just want to capture the (\w*) group. also tried with /(?:[^\w]*(\w*)[^\w]*)?/g and it's the same...
What about something like
' hi,everyone just testing'.replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
If you want to process each word, you can use
' hi,everyone just testing'.replace(/\w+/g, function(word) {
// do something with each word like
return word.toUpperCase();
});
When you use the global modifier (g), then the capture groups are basically ignored. The returned array will contain every match of the whole expression. It looks like you just want to match consecutive word characters, in which case \w+ suffices:
>>> ' hi,everyone just testing'.match(/\w+/g)
["hi", "everyone", "just", "testing"]
See here: jsfiddle
function capitaliseFirstLetter(match)
{
return match.charAt(0).toUpperCase() + match.slice(1);
}
var myRe = /\b(\w+)\b/g;
var result = "hi everyone, just testing".replace(myRe,capitaliseFirstLetter);
alert(result);
Matches each word an capitalizes.
I'm unclear about what you're really after. Why is your regex not working? Or how to get it to work? Here's a way to extract words and spaces in your sentence:
var str = ' hi,everyone just testing';
var words = str.split(/\b/); // [" ", "hi", ",", "everyone", " ", "just", " ", "testing"]
words = word.map(function properCase(word){
return word.substr(0,1).toUpperCase() + word.substr(1).toLowerCase();
});
var sentence = words.join(''); // back to original
Note: When doing any string manipulation, replace will be faster, but split/join allows for cleaner, more descriptive code.

How to split javascript string into a max of 2 parts?

I have strings like this
FOO hello world
BAR something else
BISCUIT is tasty
CAKE is tasty too
The goal is to split string once after the first word. So far I'm using this
# coffeescript
raw = 'FOO hello world'
parts = raw.split /\s/
[command, params] = [parts.shift(), parts.join(' ')]
command #=> FOO
params #=> hello world
I don't like this for two reasons:
It seems inefficient
I'm rejoining the string with a ' ' character. The real string parameters can be split by either a ' ' or a \t and I'd like to leave the originals intact.
Any ideas?
Try this out:
[ command, params ] = /^([^\s]+)\s(.*)$/.exec('FOO hello world').slice(1);
You can use indexOf to find the space (for \t - handle it separately and choose the smaller of the two indexes) and then slice there:
var command;
var params = '';
var space = raw.indexOf(" ");
if(space == -1) {
command = e.data;
} else {
command = raw.slice(0, space);
params = raw.slice(space + 1);
}
Also, it's a lot quicker, as it doesn't uses regular expressions.
Variant of #NathanWall's answer without unnecessary variable:
[command, params] = /([^\s]+)\s(.+)/.exec('FOO hello world').slice(1)
Here a simple code :
var t = "FOO hello world";
var part1 = t.match(/(\w+\s)/)[0];
var part2 = t.replace(part1,"");
part1 will contain "FOO " and part2 "hello world"
Here's how I would do it:
let raw = "FOO hello world"
raw.split(" ")
.filter((part, index) => index !== 0)
.join(" ")
Baically, take the word, split it by the space (or whatever), then filter the first one away, then join it back up.
I find this more intuitive than doing the slicing above.
Another option is:
# coffeescript
raw = 'FOO hello world'
[command, params] = raw.split(/\s/, 2)
command #=> FOO
params #=> hello world
Which I thin't looks more semantic than your original code.

Categories

Resources