I'm trying to extract all substrings that start with ! for a string in Javascript. for example if my string is:
Hi Jack !Smile, This is a !silly text to try out this !Code!
So the output should be an array with elements:
var arr = ['Smile', 'Silly', 'Code']
The reason I'm doing is because I want to convert these codes into emoticons for my chatroom and "!" is an indicator that this is an emoticon code. Is there any fast and optimal to do this and not go through every word using a for loop?
I think a simple regex along with an array processing should do it
var string = "Hi Jack !Smile, This is a !silly text to try out this !Code!";
var match = string.match(/!(.+?)\b/g),
array = match ? match.map(function(val) {
return val.substring(1)
}) : [];
snippet.log(JSON.stringify(array))
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can use the following regex
!(.+?)\b
Related
i want to replace multiple patterns in the same string using regex and javascript.
What i am trying to do?
i have a string for example
string = "hello i am [12#fname lname] and i am referring this user [23#fname1 lname1]"
now i get all the strings with [] using regex
const get_strings_in_brackets = string.match(/\[(\d+#[\w\s]+)]/g);
so get_strings_in_brackets will have
["[12#fname lname]", "[23#fname1 lname1]"]
now i want these to be replaced with string "<some-tag id="12"/> "<some-tag id="23"/> in the string "hello i am [12#fname lname] and i am referring this user [23#fname1 lname1]"
also this number 12 in this string "<some-tag id="12"/> is got from the string ["[12#fname lname]" before # character.
What i have tried to do?
i have tried to replace for only one string withing brackets meaning for the example below
string ="hello i am [12#fname lname1]"
const extracted_string_in_brackets = string.match(/\[(\d+#[\w\s]+)]/g);
const get_number_before_at_char =
extracted_string_in_brackets[0].substring(1,
extracted_string_in_brackets[0].indexOf('#'));
const string_to_add_in_tag = `<some-tag
id="${get_number_before_at_char}"/>`;
const final_string = string.replace(extracted_string_in_brackets,
string_to_add_in_tag);
The above code works if i have only one string within square brackets. But how do i do it with multiple strings in brackets and replacing that with tag string that is for example .
Could someone help me solve this. thanks.
Just use a group reference in your replacement:
string = "hello i am [12#fname lname] and i am referring this user [23#fname1 lname1]"
newstr = string.replace(/\[(.+?)#(.+?)\]/g, '<some-tag id="$1"/>')
console.log(newstr)
When # comes in string, I want to split it on new line using JavaScript.
Please help me.
Sample input:
This application helps the user to instantiate #Removed#Basic#afdaf#Clip#Python#matching of many parts#
Expected output:
This helps the user to instantiate
Removed
Basic
afdaf
Clip
Python
matching of many parts
you can simply replace '#' by '\n'
var mainVar = 'This application helps the user to instantiate#Removed#Basic#afdaf#Clip#Python#matching';
console.log(mainVar.replace(/[^\w\s]/gi, '\n'));
Convert a string into array and loop through the array and print values one by one.
var str = "helps the user to instantiate #Removed#Basic#afdaf#Clip#Python#matching of many parts#";
str.split("#").forEach(function(entry) {
console.log(entry);
});
You can try this:
You should use the string replace function, with a single regex. Assuming by special characters
var str = "This application helps the user to instantiate #Removed#Basic#afdaf#Clip#Python#matching of many parts#";
console.log(str.replace(/[^a-zA-Z ]/g, "\n"));
The below solution will split based on the # and store it in an array.
This solution will come in handy with splitting strings.
var sentence = '#Removed#Basic#afdaf#Clip#Python#matching of many parts#'
var newSentence = [];
for(var char of sentence.split("#")){
console.log(char); // This will print each string on a new line
newSentence.push(char);
}
console.log(newSentence.join(" "));
I've looked all over the web but couldnt find a good answer to this. I need to write a function that finds the first word in a string/sentence. Its in relation to a html/css/javascript assignment, where i need to color or mark the first word in a long string, containing a story.
I'm thinking a simple for loop could do it, but cant get it to work.
The String global object is a constructor for strings or a sequence of characters.
in javascript String object has methods on his prototype - MDN - String
String.prototype.split() - Reference (MDN)
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
because you want to split by words, you should split string by "space".
as you can see split method on string return an array, so the first item in array will be the first word.
'Some String Here'.split(' ')[0];
Good Luck!
// Get Results Element
var div = document.querySelector('.results');
// Some string
var someString = 'Hi Hello JavaScript World';
function renderFirstWorkAsMarked(string, color) {
var splitedString = string.split(' ');
var wrapper = document.createElement('div')
var marked = document.createElement('span');
var restString = document.createTextNode(splitedString.slice(1).join(' '))
marked.style.color = color;
marked.innerHTML = `${splitedString[0]} `;
wrapper.appendChild(marked)
wrapper.appendChild(restString)
return wrapper
}
// append on screen
div.append(renderFirstWorkAsMarked(someString, 'red'))
// This is example code for your full question.
<div class="results"></div>
This will do the trick. It splits the string by the whitespace and then provides you the first word using the index.
"Plane Jane Mane".split(" ")[0]
Here's an example, the first console log will show you the formed array, and the second will select the first word in the array:
var word = "Plane Jane Mane"
console.log(word.split(" "))
console.log(word.split(" ")[0])
I answer your question with ES6 arrow function. see below code:
const firstWord = string => string.split(' ')[0];
Or you can use regex but I prefer the first function:
const firstWord = string => string.match(/^[\w\d]+/gs)[0];
let string = 'This is a sentence';
let word = string.split(' ')[0];
console.log(word);
Firstly, split sentences. Secondly, Split words and take first:
yourtext
.split(/(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s/g)
.map(w => w.split(/((\b[^\s]+\b)((?<=\.\w).)?)/g)[1])
Example
I've looked all over the web but couldnt find a good answer to this. I need to write a function that finds the first word in a string/sentence. Its in relation to a html/css/javascript assignment, where i need to color or mark the first word in a long string, containing a story.
I'm thinking a simple for loop could do it, but cant get it to work.
Result
I've,I,Its,I'm
I have this following javascript variable.
var data = "ashley, andy, juana"
i Want the above data to look like this.
var data = "Sports_ashley, Sports_andy, Sports_juana"
It should be dynamic in nature. any number of commas can be present in this variable.
Can someone let me an easy way to achieve this please.
Using .replace should work to add sports before each comma. Below I have included an example.
var data = data.replace(/,/g , ", Sports_");
In that example using RegExp with g flag will replace all commas with Sports, instead of just the first occurrence.
Then at the end you should just be able to append Sports to the end like so.
data = "Sports_" + data;
Probably an overkill, but here is a generic solution
function sportify(data) {
return data
.split(/\s*,\s*/g) //splits the string on any coma and also takes out the surrounding spaces
.map(function(name) { return "Sports_" + name } ) //each name chunk gets "Sport_" prepended to the end
.join(", "); //combine them back together
}
console.log(sportify("ashley, andy, juana"));
console.log(sportify("ashley , andy, juana"));
String.replace()
Array.map()
Array.join()
EDIT: updated with the new version of the OP
Use a regex to replace all occurrences of a , or the beginning of the string using String#replace()
var input = "ashley, andy, juana"
var output = input.replace(/^|,\s*/g, "$&Sports_");
console.log(output);
Ok, So I hit a little bit of a snag trying to make a regex.
Essentially, I want a string like:
error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z
to be parsed to read
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
ateTo=2013-01-16T05:00:00.000Z
So I want it to pull known keywords, and ignore other strings that have =.
My current regex looks like this:
(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=[\w\s\f\-\:]+(?![(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=])
So I'm using known keywords to be used dynamically so I can list them as being know.
How could I write it to include this requirement?
You could use a replace like so:
var input = "error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z";
var result = input.replace(/\s*\b((?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/g, "\n$1");
result = result.replace(/^\r?\n/, ""); // remove the first line
Result:
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
dateTo=2013-01-16T05:00:00.000Z
Another way to tokenize the string:
var tokens = inputString.split(/ (?=[^= ]+=)/);
The regex looks for space that is succeeded by (a non-space-non-equal-sign sequence that ends with a =), and split at those spaces.
Result:
["error=some=new item", "user=max", "dateFrom=2013-01-15T05:00:00.000Z", "dateTo=2013-01-16T05:00:00.000Z"]
Using the technique above and adapt your regex from your question:
var tokens = inputString.split(/(?=\b(?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/);
This will correctly split the input pointed out by Qtax mentioned in the comment: "error=user=max foo=bar"
["error=", "user=max foo=bar"]