Detect Specific Words on string - javascript

Here is my String:
var str1 = '#hello, world how are you. I #am good';
Now I want to split # prefixed worlds like #hello, #am etc to be stored in an array.
Desired output will be
var str2 = [#hello, #am];
can anyone guide me.

With a simple regex
\B#\w+/g
without a function :
var str1 = '#hello, world how are you. I #am good';
console.log(str1.match(/\B#\w+/g));
with a function :
getMatchedStrings("#hello, #world how are you. I #am good");
function getMatchedStrings(input){
var re = /\B#\w+/g;
var specials = [];
var match;
while(match = re.exec(input)){
specials.push(match[0]);
}
console.log(specials)
}
You may try more regex here :
https://regex101.com/r/rBuMrY/1
Output:
["#hello", "#am"]

Check this out, i add comment for easy understand this code
var str = '#hello, world how are you. I #am good';
str = str.split(' '); // split text to word array
str = str.filter(function(word){
return word.includes('#'); // check words that using #
}).map(function (word) {
return word.replace(/[^a-zA-Z^# ]/g, "") // remove special character except #
});
console.log(str) // show the data

var str1 = '#hello, world how are you. I #am good';
var reg = /(?:^|[ ])#([a-zA-Z]+)/;
var str = str1.split(" ");
//console.log(str.length);
for (var i = 0; i < str.length; i++) {
if (reg.test(str[i])) {
//your code to store match value in another array
console.log(str[i]);
}
}

Use Regex, I am not really good at it but just a try
var str1 = '#hello, world how are you. I #am good';
var str2 = str1.match(/#(.+?)[^a-zA-Z0-9]/g).map(function(match) { return match.slice(0, -1); });
console.log(str2);

Related

Insert characters on start and end of regex result on javascript

i have problems inserting character in result of regex. I need do some like this:
var str = "Hello world, hello";
var regX = /he/ig;
The result have to be a string like this:
console.log(result);
<mark>He</mark>llo world, <mark>he</mark>llo"
I tried using this code:
r = /he/ig;
str = "Hello world Hello";
var match, indexes = [];
while (match= r.exec(str)){
indexes.push([match.index, match.index+match[0].length]);
}
indexes.forEach( (element) => {
var strStart = str.substring(0,element[0]);
var strBetween = "<mark>"+str.substring(element[0],element[1])+"</mark>";
var strEnd = str.substring(element[1],str.length);
str = strStart.concat(strBetween,strEnd);
});
console.log(str); //<mark>He</mark>llo worl<mark>d </mark>Hello
I understand where is the error, but i don't kwon how solve that.
You can do this with the .replace() method:
var str = "Hello world hello";
var result = str.replace(/he/ig, "<mark>$&</mark>");
The $& in the replacement string means that the matched text should be substituted.

Make string comma delimited in JavaScript

I have a string:
var myStr = 'This is a test';
I would like to make it comma delimited via JavaScript, like so:
var myNewStr = 'This, is, a, test';
What is the best way to accomplish this via JavaScript?
I know I can trim the commas like so:
var myStr = myNewStr.split(',');
And that would give me this:
myStr = 'This is a test';
But I am wanting to do the opposite of course, by adding commas.
You could just replace with regex - it is shorter and no need to split.
var myNewStr = myStr.replace(/ /g,', ');
In case you could also face the string with leading / trailing spaces, just trim it beforehand.
var myNewStr = myStr.trim().replace(/ /g,', ');
Try this - var myNewStr = myStr.split(' ').join(', ')
You could use a regular expression with a positive lookahead and replace then with a comma.
console.log('This is a test'.replace(/(?= .)/g, ','));
console.log('This is a test '.replace(/(?= .)/g, ','));
Use String.replace:
var myStr = 'This is a test';
var myNewStr=myStr.replace(/ /g,', ');
You could use the replace function to replace the spaces with commas:
var myStr = myNewStr.replace(' ', ',');
You could also use:
var myStr = myNewStr.split(' ');
Here is a way to do it without using the standard methods.
var myStr = "THIS IS A TEST";
before.innerHTML = myStr;
var parts = [];
var buffer = '';
for(var i = 0; i < myStr.length; i++) {
if(myStr[i] == ' ') {
parts.push(buffer);
buffer = '';
continue;
} else {
buffer += myStr[i];
}
}
parts.push(buffer)
var myNewStr = parts.join(', ');
after.innerHTML = myNewStr;
<div><b>Before</b></div>
<div id="before"></div>
<div><b>After</b></div>
<div id="after"></div>
The solution using String.trim and String.replace functions:
var myStr = ' This is a test ',
myNewStr = myStr.trim().replace(/([^\s]+\b)(?!$)/g, "$&,");
// $& - Inserts the matched substring.
console.log(myNewStr); // "This, is, a, test"

JavaScript get character in sting after [ and before ]

I have some strings like:
str1 = "Point[A,B]"
str2 = "Segment[A,B]"
str3 = "Circle[C,D]"
str4 = "Point[Q,L]"
Now I want to have function that gives me character after "[" and the character before "]". How could I make something like that ?
try this one...
var str = "Point[A,B]";
var start_pos = str.indexOf('[') + 1;
var end_pos = str.indexOf(']',start_pos);
var text_to_get = str.substring(start_pos,end_pos)
alert(text_to_get);
You'd need regex to do that
var matches = /\[(.*?)\]/.exec(str1);
alert(matches[1]);
You can use match() to extract the characters:
str.match(/\[(.*)\]/)[1]
A safer way would be:
var matches = str.match(/\[(.*)\]/);
if(matches) {
var chars = matches[1];
}
Here's an approach which avoids regex.
var str = "Point[A,B]";
var afterOpenBracket = str.split("[")[1]; // returns "A,B]"
var bracketContents = afterOpenBracket.split("]")[0]; // returns "A,B"
There, pretty simple! bracketContents now contains the entirety of the text between the first set of brackets.
We can stop here, but I'll go a step further anyway and split up the parameters.
var parameters = bracketContents.split(","); // returns ["A", "B"]
Or in case u have more [A,C,D,B] and don't want to use regex:
var str1 = "Point[A,C,D,B]";
function extract(str1){
var a = str1.charAt(str1.indexOf('[')+1);
var b = str1.charAt(str1.indexOf(']')-1);
return [a, b];
//or
//a.concat(b); //to get a string with that values
}
console.log(extract(str1));

How do I split a string and then match them with another string

Let's sat I have the sentence "I like cookies" and the sentence "I_like_chocolate_cookies".
How do I split the string "I like cookies" and check if the words exists in the second sentence?
Like this
var words = "I like cookies".replace(/\W/g, '|');
var sentence = "I_like_chocolate_cookies";
console.log(new RegExp(words).test(sentence));
https://tinker.io/447b7/1
Here's some sample code:
str1 = 'I like cookies'
str2 = 'I_like_chocolate_cookies'
// We convert the strings to lowercase to do a case-insensitive check. If we
// should be case sensitive, remove the toLowerCase().
str1Split = str1.toLowerCase().split(' ')
str2Lower = str2.toLowerCase()
for (var i = 0; i < str1Split.length; i++) {
if (str2Lower.indexOf(str1Split[i]) > -1) {
// word exists in second sentence
}
else {
// word doesn't exist
}
}
Hope this helps!
like this?
var x ="i like grape";
var c ="i_don't_like";
var xaar = x.split(' ');
for(i=0;i<xaar.length;i++){
if(c.indexOf(xaar[i])>-1) console.log(xaar[i]);
}
var foo = "I_like_chocolate_cookies";
var bar = "I like chocolate cookies";
foo.split('_').filter(function(elements) {
var duplicates = []
if(bar.split().indexOf(element) != -1) {
return true;
}
});

Capitalize the first letter of every word

I want to use a javascript function to capitalize the first letter of every word
eg:
THIS IS A TEST ---> This Is A Test
this is a TEST ---> This Is A Test
this is a test ---> This Is A Test
What would be a simple javascript function
Here's a little one liner that I'm using to get the job done
var str = 'this is an example';
str.replace(/\b./g, function(m){ return m.toUpperCase(); });
but John Resig did a pretty awesome script that handles a lot of cases
http://ejohn.org/blog/title-capitalization-in-javascript/
Update
ES6+ answer:
str.split(' ').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');
There's probably an even better way than this. It will work on accented characters.
function capitalizeEachWord(str)
{
var words = str.split(" ");
var arr = [];
for (i in words)
{
temp = words[i].toLowerCase();
temp = temp.charAt(0).toUpperCase() + temp.substring(1);
arr.push(temp);
}
return arr.join(" ");
}
"tHiS iS a tESt".replace(/[^\s]+/g, function(str){
return str.substr(0,1).toUpperCase()+str.substr(1).toLowerCase();
});
Other variant:
"tHiS iS a tESt".replace(/(\S)(\S*)/g, function($0,$1,$2){
return $1.toUpperCase()+$2.toLowerCase();
});
This is a simple solution that breaks down the sentence into an array, then loops through the array creating a new array with the capitalized words.
function capitalize(str){
var strArr = str.split(" ");
var newArr = [];
for(var i = 0 ; i < strArr.length ; i++ ){
var FirstLetter = strArr[i].charAt(0).toUpperCase();
var restOfWord = strArr[i].slice(1);
newArr[i] = FirstLetter + restOfWord;
}
return newArr.join(' ');
}
take a look at ucwords from php.js - this seems to be kind of what you're looking for. basically, it's:
function ucwords (str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
note that THIS IS A TEST will return THIS IS A TEST so you'll have to use it like this:
var oldstring = "THIS IS A TEST";
var newstring = ucwords(oldstring.toLowerCase());
or modify the function a bit:
function ucwords (str) {
str = (str + '').toLowerCase();
return str.replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
var oldstring = "THIS IS A TEST";
var newstring = ucwords(oldstring); // This Is A Test
This will capitalize every word seperated by a space or a dash
function capitalize(str){
str = str.toLowerCase();
return str.replace(/([^ -])([^ -]*)/gi,function(v,v1,v2){ return v1.toUpperCase()+v2; });
}
Examples :
i lOvE oRanges => I Love Oranges
a strAnge-looKing syntax => A Strange-Looking Syntax
etc
If you don't mind using a library, you could use Sugar.js capitalize()
capitalize( all = false ) Capitalizes the first character in the
string and downcases all other letters. If all is true, all words in
the string will be capitalized.
Example:
'hello kitty'.capitalize() -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'
you can also use below approach using filter:
function Ucwords(str){
var words = str.split(' ');
var arr = [];
words.filter(function(val){
arr.push(val.charAt(0).toUpperCase()+ val.substr(1).toLowerCase());
})
console.log(arr.join(" ").trim());
return arr.join(" ").trim();
}
Ucwords("THIS IS A TEST") //This Is A Test
Ucwords("THIS ") //This
{
String s = "this is for testing";
String sw[] = s.split("\\s");
String newS = "";
for(int i=0; i<=sw.length-1; i++)
{
String first = sw[i].substring(0,1);
String last = sw[i].substring(1);
newS+= first.toUpperCase()+last+" ";
}
System.out.println(newS);
}

Categories