Javascript: split a string according to two criteria? - javascript

I am trying to count the number of sentences in a paragraph. In the paragraph, all sentences end with either ''.'' or ''!''.
My idea is to first split the paragraph into strings whenever there's a ''.'' or ''!'' and then count the number of splitted strings.
I have tried
.split('.' || '!')
but that does not work. It only splits strings whenever there is a ''.''
May I know how to deal with this?

Just use a Regexp, it's pretty simple ;)
const example = 'Hello! You should probably use a regexp. Nice isn\'t it?';
console.log(example.split(/[.!]/));

You will need to use a regex for this.
The following should work:
.split(/\.|!/)

You can use regex /\.|!/ in split() as str.split(/\.|!/) :
var str = 'some.string';
console.log(str.split(/\.|!/));
str = 'some.string!name';
console.log(str.split(/\.|!/));

const sampleString = 'I am handsome. Are you sure?! Just kidding. Thank you.';
const result = sampleString.split(/\.|!/)
console.log(result);
// to remove elements that has no value you can do
const noEmptyElements = result.filter(str => str);
console.log(noEmptyElements);

Try below code it will give you an exact count of sentences in the paragraph.
function count(string,char) {
var re = new RegExp(char,"gi");
return string.match(re).length;
}
function myFunction() {
var str = 'but that! does! not work. It only splits strings whenever there is a. ';
console.log(count(str,'[.?!]'));
}

Related

Cant make regex work to remove the first white space character

I have the following div:
<div data-test="([1] Hello World), ([2] Foo Bar)"></div>
Now what I am trying to do is to find the cleanest way to break the string into the following pieces:
array ["1", "Hello World", "2", "Foo Bar"];
How can I achieve this the proper and fast way?
I managed to get close but my solution seems somewhat ugly and doesnt work as expected.
var el = document.getElementsByTagName("div")[0];
data = el.getAttribute('data-test');
list = data.replace(/[([,]/g, '').split(/[\]\)]/);
for(str of list) {
str = str.trim();
}
I still get the spaces at the start of each string. I dont really want to use trim or anything similar. I tried to add a whitespace character to my regex s/ but that was a bad idea too.
The below function should work.
function strToArr(str) {
var arr = [];
var parts = str.split(', ');
parts.forEach(part => {
var digit = part.match(/(\d+)/g)[0];
var string = part.match(/(\b[a-zA-Z\s]+)/g)[0];
arr.push(digit, string);
});
return arr;
}
var text = '([1] Hello World), ([2] Foo Bar)';
var textReplaced = text.replace(/\(\[([^\]])\]\s([^)]+)\)/g, '$1, $2');
var array = textReplaced.split(', ');
console.log(array);
Without any cycle.
You can try the following regular expression:
list = data.replace(/^\(\[|\)$/g, '').split(/\] |\), \(\[|\] /);
Two steps:
remove the heading "(["and tailing ")"
split the string into the parts you want with the delimiter symbols
Suppose the format of the string is fixed.

How make lodash _.replace all occurrence in a string?

How to replace each occurrence of a string pattern in a string by another string?
var text = "azertyazerty";
_.replace(text,"az","qu")
return quertyazerty
You can also do
var text = "azertyazerty";
var result = _.replace(text, /az/g, "qu");
you have to use the RegExp with global option offered by lodash.
so just use
var text = "azertyazerty";
_.replace(text,new RegExp("az","g"),"qu")
to return quertyquerty
I love lodash, but this is probably one of the few things that is easier without it.
var str = str.split(searchStr).join(replaceStr)
As a utility function with some error checking:
var replaceAll = function (str, search, replacement) {
var newStr = ''
if (_.isString(str)) { // maybe add a lodash test? Will not handle numbers now.
newStr = str.split(search).join(replacement)
}
return newStr
}
For completeness, if you do really really want to use lodash, then to actually replace the text, assign the result to the variable.
var text = 'find me find me find me'
text = _.replace(text,new RegExp('find','g'),'replace')
References:
How to replace all occurrences of a string in JavaScript?
Vanilla JS is fully capable of doing what you need without the help of lodash.
const text = "azertyazerty"
text.replace(new RegExp("az", "g"), "qu")

how to get numbers from a string in javascript?

I have
"id": 1468306
inside of a string, how can I use regular expression to get the number 1468306 for it?
You can use this regex:
/: (\d+)/
as in:
s = '"id": 1468306';
r = /: (\d+)/;
console.log(r.exec(s)[1]);
Output:
1468306
you can use parseInt() method in javascript as follows:
var str = parseInt(id);
Following code may help you:
var input = '"id": 1468306';
var matches = input.match(/"id": (\d+)/);
var id = matches[1];
The id get the required number.
JSON.parse("{" + yourString + "}").id
Will be your number if you have that in a String.
Fiddle: http://jsfiddle.net/SfeMh/
var regEx = /\d+/g;
var str = '"id": 1468306';
var numbers = str.match(regEx);
alert(numbers); // returns 1468306
It looks like you're trying to parse a JSON String. Try this way as already mentioned:
var parsedObj = JSON.parse(myJSONString);
alert(parsedObj.id); // returns 1468306
This will match in this cases
id : 156454;
id :156454;
id:156454;
/id\s?[:]\s?[0-9]+/g.match(stringhere)
Alright, my JSON answer still stands, use it if that's your full string you're giving us in the question. But if you really want a regex, here's one that will search for "id" and then find the number after.
parseInt(yourString.match(/("id"\s?:\s?)(\d+)/)[2])
Fiddle: http://jsfiddle.net/tS9M4/

javascript split with regex

I would like to split characters into array using javascript with regex
foo=foobar=&foobar1=foobar2=
into
foo, foobar=,
foobar1, foobar2=
Sorry for not being clear, let me re describe the scenario.
First i would split it by "&" and want to post process it later.
str=foo=foobar=&foobar1=foobar2=
var inputvars=str.split("&")
for(i=0;i<inputvars.length;i++){
var param = inputvars[i].split("=");
console.log(param);
}
returns
[foo,foobar]
[]
[foobar1=foobar2]
[]
I tried to use .split("=") but foobar= got splited out as foobar.
I essentially want it to be
[foo,foobar=]
[foobar1,foobar2=]
Any help with using javascript to split first occurence of = only?
/^([^=]*)=(.*)/.exec('foo=foobar=&foobar1=foobar2=')
or simpler to write but using the newer "lazy" operator:
/(.*?)=(.*)/.exec('foo=foobar=&foobar1=foobar2=')
from malvolio, i got to conclusion below
var str = 'foo=foobar=&foobar1=foobar2=';
var inputvars = str.split("&");
var pattern = /^([^=]*)=(.*)/;
for (counter=0; counter<inputvars.length; counter++){
var param = pattern.exec(inputvars[counter]);
console.log(param)
}
and results (which is what i intended)
[foo,foobar=]
[foobar1,foobar2=]
Thanks to #malvolio hint of regex
Cheers

group parts of a string into an array element

If I have a string... abcdefghi
and I want to use regex to load every elemnent into an array but I want to be able to stick anything connected by plus sign into the same element... how to do that?
var mystring = "abc+d+efghi"
output array ["a","b","cde","f","g","h","i"]
One way to do it:
var re = /([^+])(?:\+[^+])*/g;
var str = 'abcd+e+fghi';
var a = str.match(re).map(function (s) { return s.replace(/\+/g, ''); });
console.log(a);
The value of a[3] should now be 'def'.
http://jsfiddle.net/rbFwR/2
You can use this expression, to produce [a][b][c+d+e][f][g][h][i].
mystring.split ("(.\+)*.")
Next, replace any + characters with empty on the resulting list.
mystring.split("\\+")
Click here for more information.

Categories