Splitting string by {0}, {1}...{n} and replace with empty string - javascript

I have the following String:
var text = "Hello world! My name is {0}. How {1} can you be?"
I wanna find each of the {n} and replace them with an empty string. I'm totally useless with regex and tried this:
text = text.split("/^\{\d+\}$/").join("");
I'm sure this is an easy answer and probably exist some answer already on SO but I'm not sure what to search for. Not even sure what the "{" are called in english.
Please (if possible) maintain the use of "split" and "join".
Thanks!

You could achieve this through string.replace function.
string.replace(/\{\d+\}/g, "")
Example:
> var text = "Hello world! My name is {0}. How {1} can you be?"
undefined
> text.replace(/\{\d+\}/g, "")
'Hello world! My name is . How can you be?'
Through string.split. You just need to remove the anchors. ^ asserts that we are at the start and $ asserts that we are at the end. Because there isn't only a string {num} exists in a single line, your regex fails. And also remove the quotes which are around the regex delimiter /
> text.split(/\{\d+\}/).join("");
'Hello world! My name is . How can you be?'

You were close. What you want is: text = text.split(/\{\d+\}/).join("");
The two things that you missed were:
^ = the start of the string and $ = the end of the string. Since there are other characters around the pattern that you are trying to match, you don't want those.
if you are using a regular expression in the split() method, you need to use a RegExp object, not a string. Removing the "'s and just having the expression start and end with / will define a RegExp object.
I would actually agree with the others that the replace() method would be a better way to do what you are trying to accomplish, but if you want to use split() and join(), as you've stated, this is the change that you need.

You can just use replace mehthod:
var repl = text.replace(/\{\d+\} */g, '');
//=> "Hello world! My name is . How can you be?"

Related

How to add letters / words / characters to a special word in a string in javascript?

Let us consider we have a string str and a function addify() and we can do something like this with it :
var str = "I am #java";
console.log(addify(str, "script");
//=> I am #javascript
So, you may understand what happened ! The addify() finds all the words with the special character # and then adds our desired words or letter or any character to it. Another example :
var str = "I wrote a #s in #javas";
console.log(addify(str, " cript");
//=> I wrote a #script in #javascript
So, can anyone teach me how to make the addify() function ?
Thanks in advance
Find substring in Javascript and prepend/append some characters
StackOverflow to the rescue!
At the provided link you can find a regex example on how you can identify a special character within a provided string and then edit the result using the string .replace() method...
Quick breakdown of the regex: find the (\w+) word after the string # which is then represented as $1 as the second parameter in the string .replace() method where you can modify the string into a new format.
Bonus points: this will only find instances where the string being searched is connected to another word. If you targeted identifier (#) exists alone, then it will not update a blank space.
function addify( str, ending ){
return str.replace(/#(\w+)/g, `#$1${ending}`);
}
console.log( addify( 'i like #cheese', 'burgers' ) );
console.log( addify( 'party # my place', 'not!' ) );

Check first character of a word in a string begins with #

A few days ago I posted a similar question, but I do not quite understand the principle. Are there good resources where the replace function combined with regular expressions is explained?
Anyways, right now I have the following problem: A string which starts with # should be placed in an link. So #test should be replaced to #test .
Also, these rules should apply:
The string can only contain one #, which is at the beginning.
If there are more strings, also replace them. I thought you can do this by putting /g behind the regex?
This is what I have so far:
value = "is #test";
var text = value.replace(/^.*(#)(\w+).*$/, "<a href='$2'>$1$2</a>");
My output
#test
EDIT:
The link is now working. However, the word "is" is missing.
You need to capture the ambient text:
value = "is #test or what";
var text = value.replace(/^(.*)#(\w+)(.*)$/, "$1<a href='$2'>#$2</a>$3");
Or just capture less:
var text = value.replace(/#(\w+)/, "<a href='$1'>#$1</a>");
When performing a .replace(), you need to include all the characters in the RegExp that you wish to replace, preserving the ones you want to keep with parentheses.
var test = 'is #test';
function makeAt(string){
return string.replace(/^.*(#)(\w+).*$/, "<a href='$2'>$1$2</a>");
}
console.log(makeAt(test));

Regex to change quoting style

In the text that I get, I want to replace all the dialogue quotes with double quotes, while keeping the single quotes used in contractions like "aren’t". I want to use a String.replace() with a regular expression to do this..
E:g:
var text = "'I'm the cook,' he said, 'it's my job.'";
console.log(text.replace(/*regEx*/, "\""));
//should return → "I'm the cook," he said, "it's my job."
Now I know a regex that works for me, at least for the example text.
console.log(text.replace(/\B'/g, "\""));
However, I wonder if there is any other regex I can use to accomplish this. Just curious.
I noticed that the regular expression you provided doesn't replace single quotes in the beginning of the string. I came up with this one instead:
var str = "'Hello', - she said\n'Hi!' - he whispered\n";
console.log(str.replace(/\B'|'\B/g, "\""));

Need a regex that finds "string" but not "[string]"

I'm trying to build a regular expression that parses a string and skips things in brackets.
Something like
string = "A bc defg hi [hi] jkl mnop.";
The .match() should return "hi" but not [hi]. I've spent 5 hours running through RE's but I'm throwing in the towel.
Also this is for javascript or jquery if that matters.
Any help is appreciated. Also I'm working on getting my questions formatted correctly : )
EDIT:
Ok I just had a eureka moment and figured out that the original RegExp I was using actually did work. But when I was replaces the matches with the [matches] it simply replaced the first match in the string... over and over. I thought this was my regex refusing to skip the brackets but after much time of trying almost all of the solutions below, I realized that I was derping Hardcore.
When .replace was working its magic it was on the first match, so I quite simply added a space to the end of the result word as follows:
var result = string.match(regex);
var modifiedResult = '[' + result[0].toString() + ']';
string.replace(result[0].toString() + ' ', modifiedResult + ' ');
This got it to stop targeting the original word in the string and stop adding a new set of brackets to it with every match. Thank you all for your help. I am going to give answer credit to the post that prodded me in the right direction.
preprocess the target string by removing everything between brackets before trying to match your RE
string = "A bc defg hi [hi] jkl mnop."
tmpstring = string.replace(/\[.*\]/, "")
then apply your RE to tmpstring
correction: made the match for brackets eager per nhahtd comment below, and also, made the RE global
string = "A bc defg hi [hi] jkl mnop."
tmpstring = string.replace(/\[.*?\]/g, "")
You don't necessarily need regex for this. Simply use string manipulation:
var arr = string.split("[");
var final = arr[0] + arr[1].split("]")[1];
If there are multiple bracketed expressions, use a loop:
while (string.indexOf("[") != -1){
var arr = string.split("[");
string = arr[0] + arr.slice(1).join("[").split("]").slice(1).join("]");
}
Using only Regular Expressions, you can use:
hi(?!])
as an example.
Look here about negative lookahead: http://www.regular-expressions.info/lookaround.html
Unfortunately, javascript does not support negative lookbehind.
I used http://regexpal.com/ to test, abcd[hi]jkhilmnop as test data, hi(?!]) as the regex to find. It matched 'hi' without matching '[hi]'. Basically it matched the 'hi' so long as there was not a following ']' character.
This of course, can be expanded if needed. This has a benefit of not requiring any pre-processing for the string.
r"\[(.*)\]"
Just play arounds with this if you wanto to use regular expressions.
What do yo uwant to do with it? If you want to selectively replace parts like "hi" except when it's "[hi]", then I often use a system where I match what I want to avoid first and then what I want to watch; if it matches what I want to avoid then I return the match, otherwise I return the processed match.
Like this:
return string.replace(/(\[\w+\])|(\w+)/g, function(all, m1, m2) {return m1 || m2.toUpperCase()});
which, with the given string, returns:
"A BC DEFG HI [hi] JKL MNOP."
Thus: it replaces every word with uppercase (m1 is empty), except if the word is between square brackets (m1 is not empty).
This builds an array of all the strings contained in [ ]:
var regex = /\[([^\]]*)\]/;
var string = "A bc defg hi [hi] [jkl] mnop.";
var results=[], result;
while(result = regex.exec(string))
results.push(result[1]);
edit
To answer to the question, this regex returns the string less all is in [ ], and trim whitespaces:
"A bc defg [hi] mnop [jkl].".replace(/(\s{0,1})\[[^\]]*\](\s{0,1})/g,'$1')
Instead of skipping the match you can probably try something different - match everything but do not capture the string within square brackets (inclusive) with something like this:
var r = /(?:\[.*?[^\[\]]\])|(.)/g;
var result;
var str = [];
while((result = r.exec(s)) !== null){
if(result[1] !== undefined){ //true if [string] matched but not captured
str.push(result[1]);
}
}
console.log(str.join(''));
The last line will print parts of the string which do not match the [string] pattern. For example, when called with the input "A [bc] [defg] hi [hi] j[kl]u m[no]p." the code prints "A hi ju mp." with whitespaces intact.
You can try different things with this code e.g. replacing etc.

Modifying a string by replacing

How can I replace some words in a string with some other words? For example:
var text1 = "This is a sentence. It is a pencil."
text2 = modify(text1);
I want text2 to be "That was a sentence. I was a pencil."
So modify function replaces This->That , is->was
To replace all instances of the substring is with was you can use the replace[MDN] method:
text2 = text1.replace(/is/g, "was");
Note that because is is a part of the word this, it will actually return
Thwas was a sentence
If you wanted to replace all instances of This to That and is to was, you could chain the calls to the replace method.
text2 = text1.replace(/This/g, "That").replace(/is/g, "was");
This will correctly do your replacement from
This is a sentence. It is a pencil.
to
That was a sentence. It was a pencil.
You can see this in action on jsFiddle.
Note that find and replace actions like this can always have unintended consequences. For example, this string
Thistles and thorns are bad for missiles and corns.
will turn into this one after your replacement:
Thatles and thorns are bad for mwassiles and corns.
This sort of thing is popularly known as the Clbuttic mistake.
text1 = text1.replace('is', 'was');
Btw, .replace accepts regular expressions as well
Utilize the javascript replace method -
http://www.w3schools.com/jsref/jsref_replace.asp
Note: To replace every occurrence of a string in JavaScript, you must provide the replace() method a regular expression with a global modifier as the first parameter.
You could use javascript's Replace function like this:
var text2 = text1.replace('is','was');

Categories

Resources